【问题标题】:How do I use Convert.ChangeType to cast to a specific class?如何使用 Convert.ChangeType 转换为特定类?
【发布时间】:2010-01-29 03:18:01
【问题描述】:

有谁知道我如何使用 Convert.ChangeType 从 XML 转换为特定的类?

例如:

我的财产

public Point Loc
{
    get { return GetValue<Point2D>("Loc"); }
    set { SetValue<Point2D>("Loc", value); }
}

我的 XML:

<Loc>
 <X>1.0</X>
 <Y>1.0</Y>   
</Loc>

调用转换:

prop.SetValue(targetObj, 
             Convert.ChangeType(xmlProperty.Value, prop.PropertyType));

我已经研究过使用 IConvertible,但没有调用任何方法。

我能找到的所有示例都使用简单类型。没有显示转换为类的实例。

谢谢,

瑞克

【问题讨论】:

    标签: c# xml reflection


    【解决方案1】:

    你认为你为什么需要Convert.ChangeType()

    当然,您可以使用以下重载的SetValue 方法在PropertyInfo 对象上调用SetValue()。:

    prop.SetValue(targetObj,xmlProperty.Value,null);
    

    但是,您首先需要使用 Activator.CreateInstance() 之类的东西创建特定类型的实例,并为 Point 设置各个属性。随后,您可以将该点对象/结构指定为 SetValue 的输入。

    【讨论】:

    • 我的要求是能够从简化的 XML 文件中读取并动态创建任何指定的对象。通过序列化创建的 xml 远非简单。通过使用 Linq-To-XML 和反射,我可以创建任何类型的简单对象。问题是如何创建需要传递复杂类型的对象。
    • 仅调用 ChangeType 会导致异常,指出无法将 Value 转换为类型 Point。文档说我的对象需要实现 IConvertible 但这也不起作用。实现 IConvertible 的方法永远不会被调用。
    猜你喜欢
    • 2013-12-21
    • 2011-07-21
    • 2021-01-11
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 2022-12-05
    相关资源
    最近更新 更多