public class MyClass1
{
public int SID{get;set;}
public string Name{get;set;} public MyClass2 cls2=new MyClass2();
}public class MyClass2
{
public int SID2{get;set;}
public string Name2{get;set;}
}我现在有一个对象MyClass1 cls1=new MyClass1();//这个对象并没有赋任何值
给这个对象的SID和Name赋值的时候我可以用
PropertyInfo property=cls1.GetType().GetProperty("SID");
property.SetValue(cls1,123,null);PropertyInfo property=cls1.GetType().GetProperty("Name");
property.SetValue(cls1,"jack",null);那么我想给cls1对象的已经声明字段cls2赋值,应该怎样赋值??(方法用泛型T定义,不可以直接赋值)
{
public int SID{get;set;}
public string Name{get;set;} public MyClass2 cls2=new MyClass2();
}public class MyClass2
{
public int SID2{get;set;}
public string Name2{get;set;}
}我现在有一个对象MyClass1 cls1=new MyClass1();//这个对象并没有赋任何值
给这个对象的SID和Name赋值的时候我可以用
PropertyInfo property=cls1.GetType().GetProperty("SID");
property.SetValue(cls1,123,null);PropertyInfo property=cls1.GetType().GetProperty("Name");
property.SetValue(cls1,"jack",null);那么我想给cls1对象的已经声明字段cls2赋值,应该怎样赋值??(方法用泛型T定义,不可以直接赋值)
MyClass1 cls1 = new MyClass1();
object obj = cls1.GetType().GetField("cls2").GetValue(cls1);
obj.GetType().GetProperty("SID2").SetValue(obj, 123, null);
object obj = cls1.GetType().GetField("cls2").GetValue(cls1);
obj.GetType().GetProperty("SID2").SetValue(obj, 123, null);就是使用反射,而且你还可以用字符串的方式传入参数,实例化对象。。
依赖注入 也是用反射,对于松耦合 有很大作用