日期:2014-05-19  浏览次数:21030 次

请教:如何利用反射在代码中自动实现类型转换?
我想实现用反射遍历一个类的所有属性,并用PropertyInfo.SetValue()方法给指定的此类实例(对象)的特定属性赋值;但问题是对象中不同属性的类型是不同的,如果要用SetValue()方法赋值,必须要对使用的数据针对属性类型进行转换

类型转换我现在在用Convert.ChangeType(),一些基本类型如STRING的自动转换都可以实现了,但问题是如果属性为枚举类型的话,直接使用Convert.ChangeType()就会报错了,代码简单描述如下:
————————————————————————————
Type   type   =   typeof(myClass);
PropertyInfo   info   =   type.GetProperty( "PropertyName ");
if(info.PropertyType.IsEnum)
{
        info.SetValue(需赋值的对象,Convert.ChangeType(数值,info.PropertyType),null);
}

public   class   myClass
{public   enum   ENUM1   {Enable,Disable};
public   enum   ENUM2     {Enable,Disable};
public   ENUM1   property1
{
get{}
set{}
}
public   ENUM2   property2
{
get{}
set{}
}
——————————————————————————————
以上代码中,info.PropertyType可以正确的得出类型名ENUM1   、ENUM2   ,但Convert.ChangeType报错说类型转换无法实现

请问有什么办法能实现类似功能呢?实现代码中自动实现类型转换,而不是将每个转换单独写代码

希望在回答时能稍微详细点,同时说明下原理最好了,毕竟授人以鱼不如授人以渔,非常感谢!

------解决方案--------------------
我以前写过类似一个方法
private void SetPropertyValue(XmlNode node,Type type,object obj)
{
Type cuType = type;//Type.GetType(type);
object[] paras = new object[node.Attributes.Count];
for( int att = 0; att < node.Attributes.Count; att ++)
{
string attText = node.Attributes[att].InnerText;
string attName = node.Attributes[att].LocalName;
PropertyInfo property = cuType.GetProperty(attName);
Type attType = property.PropertyType;
if(attType.IsEnum)
{
object enumObj = Enum.Parse(attType,attText);
paras[att] = enumObj;
}

else
paras[att] = Convert.ChangeType(attText,attType);
}
for( int att = 0; att < node.Attributes.Count; att ++)
{
object[] ps = new object[1];
ps[0] = paras[att];
string attribute = node.Attributes[att].LocalName;
cuType.InvokeMember(attribute,BindingFlags.SetProperty,null,obj,ps);
}

}
------解决方案--------------------
如果是枚举 就用
Enum.Parse