static void Main(string[] args) { Dog dObj=new Dog() { dogName = "小白", dogAge = 1 }; Type dType = dObj.GetType(); //获取字段对象 FieldInfo fieldDogName = dType.GetField("dogName"); //获取dObj对象的dogName字段值,即dObj.dogName string strName = fieldDogName.GetValue(dObj) as string; //设置dObj里dogName字段赋值 fieldDogName.SetValue(dObj,"小黑"); Console.WriteLine(dObj.dogName); Console.ReadKey(); }
反射-PropertyInfo属性对象
static void Main(string[] args) { Dog dObj = new Dog() {Name = "小白", Age = 1}; Type dType = dObj.GetType(); //获取属性对象 PropertyInfo proName = dType.GetProperty("Name"); //获取dObj对象的Name属性,即dObj.Name string strName = proName.GetValue(dObj) as string; //设置dObj里面Name属性值 proName.SetValue(dObj,"小黑"); Console.WriteLine(dObj.Name); Console.ReadKey(); }
反射-MethodInfo方法对象
static void Main(string[] args) { Dog dObj=new Dog(); Type dType = dObj.GetType(); MethodInfo method = dType.GetMethod("Smile"); //普通调用方法 object res1 = dObj.Smile("小白"); //反射调用dObj的Smile方法,即dObj.Smile("小黑") //第一个参数是实例对象,第二个参数是方法的参数数组 object res2 = method.Invoke(dObj, new object[] {"小黑"}); Console.WriteLine(res1+" \n"+res2); Console.ReadKey(); }
动态创建对象
static void Main(string[] args) { //方法一:通过Activator 动态创建对象 Type dType = typeof (Dog); //调用带两个参数的构造函数 Dog dogXB = Activator.CreateInstance(dType,new object[]{"小白",1}) as Dog; Console.WriteLine(dogXB.Name+"\t"+dogXB.Age); //方法二:使用 构造器 动态创建对象 Type dTypeXH = typeof (Dog); //获得 带两个参数的 构造函数 ConstructorInfo ctor = dType.GetConstructor(new Type[] {typeof (string), typeof (int)}); //创建 指定构造函数 Dog dogXH = ctor.Invoke(new object[] {"小黑", 2}) as Dog; Console.WriteLine(dogXH.Name+"\t"+dogXH.Age); Console.ReadKey(); }