C#: Dynamic parse from System.Type

前端 未结 6 1266
没有蜡笔的小新
没有蜡笔的小新 2020-12-23 01:59

I have a Type, a String and an Object.

Is there some way I can call the parse method or convert for that type on the string dynamically?

Basically how do I r

6条回答
  •  一生所求
    2020-12-23 02:44

    TypeDescriptor to the rescue!:

    var converter = TypeDescriptor.GetConverter(propType);
    var result = converter.ConvertFrom(myString);
    

    All primitive types (plus Nullable, and numerous other built-in types) are integrated into the TypeConverter infrastructure already, and are thus supported 'out-of-the-box'.

    To integrate a custom type into the TypeConverter infrastructure, implement your own TypeConverter and use TypeConverterAttribute to decorate the class to be converted, with your new TypeConverter

提交回复
热议问题