C#泛型字符串解析为任何对象

mik*_*ike 27 c# string generics parsing

我将对象值存储在字符串中,例如,

string[] values = new string[] { "213.4", "10", "hello", "MyValue"};
Run Code Online (Sandbox Code Playgroud)

有没有办法一般初始化适当的对象类型?例如,像

double foo1 = AwesomeFunction(values[0]);
int foo2 = AwesomeFunction(values[1]);
string foo3 = AwesomeFunction(values[2]);
MyEnum foo4 = AwesomeFunction(values[3]);
Run Code Online (Sandbox Code Playgroud)

AwesomeFunction我需要的功能在哪里 最终用途是初始化属性,例如,

MyObject obj = new MyObject();
PropertyInfo info = typeof(MyObject).GetProperty("SomeProperty");
info.SetValue(obj, AwesomeFunction("20.53"), null);
Run Code Online (Sandbox Code Playgroud)

我需要这样的功能的原因是我将所述值存储在数据库中,并希望通过查询读出它们,然后初始化对象的相应属性.这有可能吗?整个对象没有存储在数据库中,只是我想要动态读取和设置的几个字段.我知道我可以静态地做到这一点,但是这将变得乏味,难以维护,并且正在阅读具有许多不同字段/属性的容易出错的情况.

编辑:奖励积分如果AwesomeFunction可以使用自定义类,指定一个接受字符串的构造函数!

EDIT2:在我想要使用此类功能的特定情况下,可以通过PropertyType了解目标类型.我认为枚举很容易解析,例如,

Type destinationType = info.PropertyType;
Enum.Parse(destinationType, "MyValue");
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 37

也许首先要尝试的是:

object value = Convert.ChangeType(text, info.PropertyType);
Run Code Online (Sandbox Code Playgroud)

但是,这不支持通过自定义类型的可扩展性; 如果你需要那个,怎么样:

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

要么:

info.SetValue(obj, AwesomeFunction("20.53", info.PropertyType), null);
Run Code Online (Sandbox Code Playgroud)

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

  • + 1.PS:对于OP的编辑:如果除了int/double/etc之外还有其他一些自定义类,你可以编写一个相应的`TypeConverter`.检查[here](http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverterattribute.aspx)和[here](http://msdn.microsoft.com/en-us/library/ ayybcxe5.aspx). (7认同)