简体   繁体   English

如何使用Convert.ChangeType强制转换为特定类?

[英]How do I use Convert.ChangeType to cast to a specific class?

Does anyone know how I can use Convert.ChangeType to cast from XML to a specific class? 有谁知道我如何使用Convert.ChangeType从XML转换为特定的类?

For example: 例如:

My Property 我的财产

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

My XML: 我的XML:

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

Call to convert: 致电转换:

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

I have looked at using IConvertible but none of the methods are being called. 我看过使用IConvertible的方法,但是没有一个方法被调用。

All of the examples I could find are using simple types. 我可以找到的所有示例都使用简单类型。 None show casting to an instance of a class. 没有显示强制转换为类的实例。

Thank you, 谢谢,

Rick 里克

Why do you think you need Convert.ChangeType() ? 为什么您认为需要Convert.ChangeType()

Surely you could just call SetValue() on the PropertyInfo object using the following overloaded SetValue method.: 当然,您可以使用以下重载的SetValue方法在PropertyInfo对象上调用SetValue()

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

However, you will first need to create an instance of the specific type, using something like Activator.CreateInstance() and set the individual properties for the Point. 但是,您首先需要使用Activator.CreateInstance()类的方法创建特定类型的实例,并为Point设置各个属性。 Subsequently, you then assign that point object/struct as input for the SetValue as you have it. 随后,然后根据需要将点对象/结构分配为SetValue输入。

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

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