获取对象属性列表,对每一个属性赋值,该如何解决
获取对象属性列表,对每一个属性赋值
先谢谢各位。帮我看看如何实现啊。我刚才用反射,仅获取了objInit的属性的名称和传入数据的类型(http://msdn.microsoft.com/zh-cn/library/system.io.bufferedstream_members(VS.80).aspx)
可不知道如何赋值。
------解决方案--------------------
- C# code
class user { private String _name; private String _sex; private int _age; public string Name{get{return this._name;}set{this._name=value;}} public string Sex{get{return this._sex;}set{this._sex=value;}} public int Age{get{return this._age;}set{this._age=value;}} } class mark { private int _math; private int _phy; public int Math{get{return this._math;}set{this._math=value;}} public int Phy{get{return this._phy;}set{this._phy=value;}} } class Test { public Test() { user x = new user(); Object[] xx ={ "1", "2", 3 }; string[] xxx ={ "Name", "Sex", "Age" }; ff(x, xx,xxx); //调用ff(x,xx)后使得 //x.Name = "1"; //x.Sex = "2"; //x.Age = 3; mark y = new mark(); Object[] yy ={ 60,90 }; string[] yyy ={ "Math", "Phy"}; ff(y, yy,yyy); //调用 ff(y, yy);后使得 //y.Math = 60; //y.Phy = 90; } public void ff(Object objInit,Object[] obj,string[] items) { //如何写代码。objInit有哪些公共属性?objInit有哪些公共属性传入什么类型的数据?…… } }
先谢谢各位。帮我看看如何实现啊。我刚才用反射,仅获取了objInit的属性的名称和传入数据的类型(http://msdn.microsoft.com/zh-cn/library/system.io.bufferedstream_members(VS.80).aspx)
可不知道如何赋值。
------解决方案--------------------
- C# code
public void ff(Object objInit, Object[] obj, string[] items) { for (int i = 0; i < obj.Length; i++) { foreach (MemberInfo mi in objInit.GetType().GetMember(items[i])) { objInit.GetType().GetField(mi.Name).SetValue(objInit, obj[i]); } } }
------解决方案--------------------
- C# code
public void ff(Object objInit, Object[] obj, string[] items) { List<string> itemList = new List<string>(items); foreach( PropertyInfo pi in objInit.GetType().GetProperties()) { int idx = itemList.IndexOf(pi.Name); if (idx >= 0) { pi.SetValue(objInit, obj[idx], null); } } }
------解决方案--------------------
A better one :)
- C# code
public void ff(Object objInit, Object[] obj, string[] items) { for(int i=0; i < items.Length; i++) { PropertyInfo pi = objInit.GetType().GetProperty( items[i] ); if( pi != null) { pi.SetValue(objInit, obj[i], null); } } }
------解决方案--------------------
ding
------解决方案--------------------
顶一下楼上的几位