日期:2014-05-18 浏览次数:20983 次
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有哪些公共属性传入什么类型的数据?…… } }
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]); } } }
------解决方案--------------------
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 :)
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
------解决方案--------------------
顶一下楼上的几位