简体   繁体   English

如何将类型为string的对象动态转换为类型为T的对象

[英]How to dynamically cast an object of type string to an object of type T

I have this XML document 我有这个XML文档

<AdditionalParameters>
<PublishToPdf Type ="System.Boolean">False</PublishToPdf>
</AdditionalParameters>

in my code and I'm trying to build an array of arguments containing the <PublishToPdf> node. 在我的代码中,我正在尝试构建一个包含<PublishToPdf>节点的参数数组。

object test = (object) ((typeof(publishNode.Attributes["Type"].value)) publishNode.InnerText);

This breaks at compile time of course. 当然,这在编译时会中断。 I can't figure out how to cast the publishNode.InnerText('false') to a runtime defined object of type specified in the XML file and store it in an object (which will conserve the type). 我无法弄清楚如何将publishNode.InnerText('false')转换为XML文件中指定类型的运行时定义对象,并将其存储在一个对象中(这将保留该类型)。

您可以使用Convert.ChangeType

object value = Convert.ChangeType(stringValue, destinationType);

You can't do exactly what you're trying to do. 你无法完全按照自己的意愿去做。 First, the typeof keyword does not allow for dynamic evaluation at runtime. 首先, typeof关键字不允许在运行时进行动态评估。 There are means by which to do this using reflection, with methods like Type.GetType(string) , but the Type objects returned from these reflective functions can't be used for operations like casting. 有一些方法可以使用反射来实现,使用Type.GetType(string)等方法,但是从这些反射函数返回的Type对象不能用于像cast这样的操作。

What you need to do is provide a means of converting your type to and from a string representation. 您需要做的是提供一种将类型转换为字符串表示形式的方法。 There is no automatic conversion from any arbitrary type. 任何类型都没有自动转换。 For your example, you can use bool.Parse or bool.TryParse , but those are specific to the bool type. 对于您的示例,您可以使用bool.Parsebool.TryParse ,但这些特定于bool类型。 There are similar methods on most primitive types. 大多数原始类型都有类似的方法。

The simple solution, assuming there is a limited number of possible types; 简单的解决方案,假设可能的类型有限;

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM