C# generic string parse to any object

后端 未结 4 463
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-01 04:25

I am storing object values in strings e.g.,

string[] values = new string[] { \"213.4\", \"10\", \"hello\", \"MyValue\"};

is there any way to ge

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-01 04:49

    Perhaps the first thing to try is:

    object value = Convert.ChangeType(text, info.PropertyType);
    

    However, this doesn't support extensibility via custom types; if you need that, how about:

    TypeConverter tc = TypeDescriptor.GetConverter(info.PropertyType);
    object value = tc.ConvertFromString(null, CultureInfo.InvariantCulture, text);
    info.SetValue(obj, value, null);
    

    Or:

    info.SetValue(obj, AwesomeFunction("20.53", info.PropertyType), null);
    

    with

    public object AwesomeFunction(string text, Type type) {
        TypeConverter tc = TypeDescriptor.GetConverter(type);
        return tc.ConvertFromString(null, CultureInfo.InvariantCulture, text);
    }
    

提交回复
热议问题