Csharp/C#教程:C# 通过反射获取类型的字段值及给字段赋值的操作分享

举例:

存在一个类:

PublicClassStudent { publicstringname; publicintage; } Studentstu1=newStudent();

现在,我们想通过反射在运行时给stu1的name和age字段赋值,让name=“小明”,age=15,怎么做?

简单的代码如下:

...略 usingSystem.Reflection;//反射类 ...略 staticvoidMain(string[]args) { Typet=stu1.GetType(); FieldInfofiledInfo1=t.GetField(”name"); FieldInfofiledInfo2=t.GetField(”age"); fieldInfo1.SetValue(stu1,"小明"); fieldInfo2.SetValue(stu1,15); }

需要注意的是:FieldInfo的SetValue方法有可能会导致异常,比如fieldInfo2.SetValue(stu1,“15”),这句话给一个int型字段赋了string类型的值,编译是不会报错的,在运行时会抛出一个System.ArgumentException异常,请多加注意.

有了上述就是C#学习教程:C# 通过反射获取类型的字段值及给字段赋值的操作分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/903535.html

(0)
上一篇 2021年10月21日
下一篇 2021年10月21日

精彩推荐