举例:
存在一个类:
Public Class Student
{
public string name;
public int age;
}
Student stu1 = new Student();
现在,我们想通过反射在运行时给stu1的name 和 age字段 赋值,让name = “小明”,age = 15,怎么做?
简单的代码如下:
...略
using System.Reflection;//反射类
...略
static void Main(string[] args)
{
Type t = stu1.GetType();
FieldInfo filedInfo1 = t.GetField(”name");
FieldInfo filedInfo2 = t.GetField(”age");
fieldInfo1.SetValue(stu1,"小明");
fieldInfo2.SetValue(stu1,15);
}
需要注意的是:FieldInfo的SetValue方法有可能会导致异常,比如 fieldInfo2.SetValue(stu1,“15”),这句话给一个int型字段赋了string类型的值,编译是不会报错的,在运行时会抛出一个System.ArgumentException异常,请多加注意.
有了以上的了解,让我们写一个简单的动态字段赋值/取值类Dynamic
具体代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace MyUnityHelper
{
/// <