Generic type conversion FROM string

前端 未结 11 628
终归单人心
终归单人心 2020-11-27 09:47

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

11条回答
  •  抹茶落季
    2020-11-27 10:12

    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.aspx Credit to "Tuna Toksoz"

    Usage first:

    TConverter.ChangeType(StringValue);  
    

    The class is below.

    public static class TConverter
    {
        public static T ChangeType(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() where TC : TypeConverter
        {
    
            TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
        }
    }
    

提交回复
热议问题