我想实现用反射遍历一个类的所有属性,并用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报错说类型转换无法实现请问有什么办法能实现类似功能呢?实现代码中自动实现类型转换,而不是将每个转换单独写代码希望在回答时能稍微详细点,同时说明下原理最好了,毕竟授人以鱼不如授人以渔,非常感谢!
————————————————————————————
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报错说类型转换无法实现请问有什么办法能实现类似功能呢?实现代码中自动实现类型转换,而不是将每个转换单独写代码希望在回答时能稍微详细点,同时说明下原理最好了,毕竟授人以鱼不如授人以渔,非常感谢!
解决方案 »
- 用C#做出像金山毒霸2012SP3.5的关闭窗口的效果
- c#类的实例化出错
- C#中如何用JS写一个回车触发button的click事件 在线等
- 如何调试调用的WebService
- Winform table行绑定问题??
- 为何我单值绑定不行,代码如下,请指教
- ==== 请教界面(Win Form)上图形的基本思路 =====
- 通过创建ToolBar中按纽的鼠标点击动作呀
- 小正方形放入大正方形问题
- C#+Web操作Excel问题,高手出招!
- 请问更新了数据库后,要在datagridview上显示出更新结果,是应该对Adapter重载还是对dataset重构,应该怎么做?
- winform 我的 文本框很多,我已经 定好了 tabindex 了,我现在想在文本框中 按回车.自动切换到下一个 文本框
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
info.SetValue(deveice,Enum.Parse(info.PropertyType,enumIndex.ToString()),null);我好像用着两条语句解决了,感谢daguzhang(MoonWell),不过现在程序还有点小问题,解决完后确认没有疑问了就马上结贴 ^_^TO:danjiewu(阿丹)
不是很明白你的意思,我是一开始吧数据装到一个对象中的,同时存有其PropertyName,我只需要针对PropertyName找到特定对象的Property并按PropertyType转换即可,至于PropertyType和数据的对应要在其他地方约定好了如果错了只能说逻辑上的问题了