利用反射实现给多级类的属性赋值

在写oba项目的时候,以前一直考虑的实体类中忽略了拥有子类的情况,该子类可能是很多类共用的。

例如:

class B

{        

private int x;        

public int X

{            

get { return x; }            

set { x = value; }        

}    

}

class A {        

private B _b;        

public B b {            

get { return _b; }            

set { _b = value; }        

}    

}

这种情况下:如果我得到一个A的实例a,(假定当获得a实例的时候b肯定不为null)我想给该实例的a.b.X利用反射进行赋值。

实际编写如下:

static void SetValue(Object obj, string str, object value)

{            

object temp = obj;            

object key = null;            

PropertyInfo values = null;            

string[] strs = str.Split('.');            

int length = strs.Length;            

if (length > 1)

{                

for (int i = 0; i < length; i++)

{                    

key = temp;                    

PropertyInfo propinfo = temp.GetType().GetProperty(strs[i]);                    

object o = temp.GetType().InvokeMember(strs[i], BindingFlags.GetProperty, null, temp, null);                    

if (o == null)

{                        

return;                    

}                    

temp = o;                    

if (i == length - 2) {                        

values = propinfo;                    

}                

}            

}            

else {             }           

values.SetValue(key, value, null);        

}

TestDriven:

static void Main(string[] args)

{            

A a = new A();            

B b = new B();            

b.X = 1000;            

a.b = b;

           

Type t = a.GetType();            

PropertyInfo propinfo=t.GetProperty("b");

object o = t.InvokeMember("b", BindingFlags.GetProperty, null, a, null);

            if (o != null) {                 PropertyInfo propinfo2 = o.GetType().GetProperty("X");                 propinfo2.SetValue(o, 1000000, null);                 propinfo.SetValue(a, o, null);             }             SetValue(a, "b.X", 1233);             Console.Write(a.b.X);             Console.ReadLine();                    }

posted @ 2012-06-04 20:58  蜗牛超悍马  阅读(193)  评论(0编辑  收藏  举报