C#: Dynamic parse from System.Type

前端 未结 6 1274
没有蜡笔的小新
没有蜡笔的小新 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:24

    This should work for all primitive types, and for types that implement IConvertible

    public static T ConvertTo(object value)
    {
        return (T)Convert.ChangeType(value, typeof(T));
    }
    

    EDIT : actually in your case, you can't use generics (not easily at least). Instead you could do that :

    object value = Convert.ChangeType(myString, propType);
    

提交回复
热议问题