C# 泛型类型转换 FROM 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-07-31 17:19:31  来源:igfitidea点击:

Generic type conversion FROM string

提问by Rob Cooper

I have a class that I want to use to store "properties" for another class. These properties simply have a name and a value. Ideally, what I would like is to be able to add typedproperties, so that the "value" returned is always of the type that I want it to be.

我有一个类,我想用它来存储另一个类的“属性”。这些属性只有一个名称和一个值。理想情况下,我希望能够添加类型化属性,以便返回的“值”始终是我想要的类型。

The type should always be a primitive. This class subclasses an abstract class which basically stores the name and value as string. The idea being that this subclass will add some type-safety to the base class (as well as saving me on some conversion).

类型应该始终是原始类型。这个类是一个抽象类的子类,它基本上将名称和值存储为字符串。这个想法是这个子类将为基类添加一些类型安全(以及节省我的一些转换)。

So, I have created a class which is (roughly) this:

所以,我创建了一个类,它(大致)是这样的:

public class TypedProperty<DataType> : Property
{
    public DataType TypedValue
    {
        get { // Having problems here! }
        set { base.Value = value.ToString();}
    }
}

So the question is:

所以问题是:

Is there a "generic" way to convert from string back to a primitive?

有没有一种“通用”的方法可以将字符串转换回原语?

I can't seem to find any generic interface that links the conversion across the board (something like ITryParsablewould have been ideal!).

我似乎找不到任何可以全面链接转换的通用接口(像ItryParsable这样的东西本来是理想的!)。

采纳答案by lubos hasko

I am not sure whether I understood your intentions correctly, but let's see if this one helps.

我不确定我是否正确理解了您的意图,但让我们看看这是否有帮助。

public class TypedProperty<T> : Property where T : IConvertible
{
    public T TypedValue
    {
        get { return (T)Convert.ChangeType(base.Value, typeof(T)); }
        set { base.Value = value.ToString();}
    }
}

回答by Greg Hewgill

You could possibly use a construct such as a traits class. In this way, you would have a parameterised helper class that knows how to convert a string to a value of its own type. Then your getter might look like this:

您可能会使用诸如traits class 之类的构造。通过这种方式,您将拥有一个参数化的辅助类,该类知道如何将字符串转换为其自身类型的值。那么你的 getter 可能看起来像这样:

get { return StringConverter<DataType>.FromString(base.Value); }

Now, I must point out that my experience with parameterised types is limited to C++ and its templates, but I imagine there is some way to do the same sort of thing using C# generics.

现在,我必须指出,我对参数化类型的经验仅限于 C++ 及其模板,但我想有一些方法可以使用 C# 泛型来做同样的事情。

回答by dbkk

For many types (integer, double, DateTime etc), there is a static Parse method. You can invoke it using reflection:

对于许多类型(整数、双精度、日期时间等),有一个静态 Parse 方法。您可以使用反射调用它:

MethodInfo m = typeof(T).GetMethod("Parse", new Type[] { typeof(string) } );

if (m != null)
{
    return m.Invoke(null, new object[] { base.Value });
}

回答by Tim Coker

lubos hasko's method fails for nullables. The method below will work for nullables. I didn't come up with it, though. I found it via Google: http://web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspxCredit to "Tuna Toksoz"

lubos hasko 的方法对于 nullables 失败。下面的方法适用于可空值。不过我没有想出来。我是通过谷歌找到的:http: //web.archive.org/web/20101214042641/http://dogaoztuzun.com/post/C-Generic-Type-Conversion.aspx 感谢“Tuna Toksoz”

Usage first:

先用:

TConverter.ChangeType<T>(StringValue);  

The class is below.

课程如下。

public static class TConverter
{
    public static T ChangeType<T>(object value)
    {
        return (T)ChangeType(typeof(T), value);
    }

    public static object ChangeType(Type t, object value)
    {
        TypeConverter tc = TypeDescriptor.GetConverter(t);
        return tc.ConvertFrom(value);
    }

    public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter
    {

        TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
    }
}

回答by Mastahh

public class TypedProperty<T> : Property
{
    public T TypedValue
    {
        get { return (T)(object)base.Value; }
        set { base.Value = value.ToString();}
    }
}

I using converting via an object. It is a little bit simpler.

我使用通过对象进行转换。它稍微简单一点。

回答by Dinesh Rathee

TypeDescriptor.GetConverter(PropertyObject).ConvertFrom(Value)

TypeDescriptoris class having method GetConvertorwhich accept a Typeobject and then you can call ConvertFrommethod to convert the valuefor that specified object.

TypeDescriptor是具有GetConvertor接受Type对象的方法的类,然后您可以调用ConvertFrom方法来转换该value指定对象的方法。

回答by anhoppe

I used lobos answer and it works. But I had a problem with the conversion of doublesbecause of the culture settings. So I added

我使用了 lobos 答案并且它有效。但是由于文化设置,我在转换双打时遇到了问题。所以我加了

return (T)Convert.ChangeType(base.Value, typeof(T), CultureInfo.InvariantCulture);

回答by Bob C

Check the static Nullable.GetUnderlyingType. - If the underlying type is null, then the template parameter is not Nullable, and we can use that type directly - If the underlying type is not null, then use the underlying type in the conversion.

检查静态Nullable.GetUnderlyingType。- 如果底层类型为 null,则模板参数不是Nullable,我们可以直接使用该类型 - 如果底层类型不为 null,则在转换中使用底层类型。

Seems to work for me:

似乎对我有用:

public object Get( string _toparse, Type _t )
{
    // Test for Nullable<T> and return the base type instead:
    Type undertype = Nullable.GetUnderlyingType(_t);
    Type basetype = undertype == null ? _t : undertype;
    return Convert.ChangeType(_toparse, basetype);
}

public T Get<T>(string _key)
{
    return (T)Get(_key, typeof(T));
}

public void test()
{
    int x = Get<int>("14");
    int? nx = Get<Nullable<int>>("14");
}

回答by Todd Menier

Yet another variation. Handles Nullables, as well as situations where the string is null and T is notnullable.

又一个变种。处理空值,以及字符串为空且 T不可空的情况。

public class TypedProperty<T> : Property where T : IConvertible
{
    public T TypedValue
    {
        get
        {
            if (base.Value == null) return default(T);
            var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);
            return (T)Convert.ChangeType(base.Value, type);
        }
        set { base.Value = value.ToString(); }
    }
}

回答by Ghominejad

With inspiration from the Bob's answer, these extensions also support null value conversion and all primitive conversion back and fourth.

Bob回答的启发,这些扩展还支持空值转换和所有原语来回转换。

public static class ConversionExtensions
{
        public static object Convert(this object value, Type t)
        {
            Type underlyingType = Nullable.GetUnderlyingType(t);

            if (underlyingType != null && value == null)
            {
                return null;
            }
            Type basetype = underlyingType == null ? t : underlyingType;
            return System.Convert.ChangeType(value, basetype);
        }

        public static T Convert<T>(this object value)
        {
            return (T)value.Convert(typeof(T));
        }
}

Examples

例子

            string stringValue = null;
            int? intResult = stringValue.Convert<int?>();

            int? intValue = null;
            var strResult = intValue.Convert<string>();