89//90//System.Reflection.TargetInvocationException:91//设置属性值时出错,表示当前实例的确切运行时类型,2627//下面使用静态方法GetType(从Object基类派生的所有类型都继承该方法)获取其类型的简单反射示例28Studentstu1=newStudent(){id=1,name="张三",length=175,datetime=DateTime.Now};//29Studentstu2=newStudent(){id=2,name="李四",length=180,datetime=DateTime.Now};//name="李四",datetime=DateTime.Now3031varlist=newList
可以使用反射动态创建类型的实例,或从现有对象获取类型并调用其方法或访问其字段和属性14///如果代码中使用了特性,51//52//返回结果:53//表示当前System.Type的所有公共属性的System.Reflection.PropertyInfo对象数组,例如,109//110//返回结果:111//指定对象的属性值,112//113//异常:114//System.ArgumentException:115//index数组不包含所需类型的参数,76//77//异常:78//System.ArgumentException:79//index数组不包含所需类型的参数,119//120//System.Reflection.TargetParameterCountException:121//index中参数的数目与已编制索引的属性所采用的参数的数目不相符,-或-未找到该属性的get访问器,125//126//System.Reflection.TargetInvocationException:127//检索属性值时出错,23//24//返回结果:25//System.Type实例,92Console.WriteLine("---------------setValue()给某属性赋值----------------");93PropertyInfostuPro=stuPropertyS.FirstOrDefault(x=>x.Name=="name");//这里是找name的属性名94stuPro.SetValue(stu1,"王五",null);95Console.WriteLine(stu1.name);969798//4、GetType()方法的解释和示例99//100//摘要:101//用索引化属性的可选索引值返回指定对象的该属性值,CoCoon,128Console.WriteLine("---------------getValue()遍历属性值----------------");129foreach(varvinstuPropertyS)//遍历属性130{131Console.WriteLine(v.GetValue(stu1,null));132}133134135Console.ReadLine();136}137}138139publicclassStudent140{141publicintid{get;set;}142publicstringname{get;set;}143publicdecimallength{get;set;}144publicDateTimedatetime{get;set;}145}146},73//74//index:75//索引化属性的可选索引值,为索引属性指定的索引值超出范围,116//117//System.Reflection.TargetException:118//该对象与目标类型不匹配,5556PropertyInfo[]stuPropertyS=stuType.GetProperties();57PropertyInfo[]listPropertyS=listType.GetProperties();5859//Console.WriteLine(stuPropertyS.Count());60//Console.WriteLine(stuPropertyS.Length);6162//3、SetValue()的解释及示例63//64//摘要:65//用索引属性的可选索引值设置该属性的值。
102//103//参数:104//obj:105//将返回其属性值的对象,1、引入命名空间:System.Reflection;程序集:mscorlib(在mscorlib.dll中)2、示例代码(主要是getType()、setValue()、getValue()方法):1usingSystem;2usingSystem.Collections.Generic;3usingSystem.Linq;4usingSystem.Reflection;5usingSystem.Text;6usingSystem.Threading.Tasks;78namespace反射9{10classProgram11{12///
可以利用反射来访问它们15///16staticvoidMain(string[]args)17{1819//1、GetType()的解释及示例20//21//摘要:22//获取当前实例的System.Type。