如何将类型为string的对象动态转换为类型为T的对象
我有这个XML文档
False
在我的代码中,我正在尝试构建一个包含节点的参数数组。
object test = (object) ((typeof(publishNode.Attributes["Type"].value)) publishNode.InnerText);
这当然在编译时打破了。 我无法弄清楚如何将publishNode.InnerText('false')
转换为XML文件中指定类型的运行时定义对象,并将其存储在对象中(这将保留类型)。
您可以使用Convert.ChangeType
:
object value = Convert.ChangeType(stringValue, destinationType);
你无法完全按照自己的意愿去做。 首先, typeof
关键字不允许在运行时进行动态评估。 有一些方法可以使用reflection来实现,使用Type.GetType(string)
等方法,但是从这些reflection函数返回的Type
对象不能用于像cast这样的操作。
您需要做的是提供一种将类型转换为字符串表示forms的方法。 任何类型都没有自动转换。 对于您的示例,您可以使用bool.Parse
或bool.TryParse
,但这些特定于bool
类型。 大多数原始类型都有类似的方法。
简单的解决方案,假设可能的类型有限;
object GetValueObject(string type, string value) { switch (type) { case "System.Boolean": return Boolean.Parse(value); case "System.Int32": return Int32.Parse(value); ... default: return value; } } var type = publishNode.Attributes["Type"].value; var value = publishNode.InnerText; var valueObject = GetValueObject(type, value);