c#中反射技术在Unity中的运用

反射技术给类赋值的好处就是可以简化代码,封装的好处就显而易见了。最直接的用途就是用在在显示配置文件的时候,个人习惯性做法是做一个VO来存储需要的数据,其代码如下:

internal class BaseItemVO {
    public string name;
    public string lockA;
}

运用反射来获取类中的字段:

public static void setValue(Object tar, String name, Object value) {
            FieldInfo fInfo = tar.GetType().GetField(name);  
            Type type = fInfo.FieldType;
            if (type==typeof(String)) {     //这里可以VO中获取字段的类型
                Console.WriteLine("this is a string");

            }
            fInfo.SetValue(tar, value);     //设置VO中的字段的值
        }

代码虽然一点点,在读取xml配置的时候非常有用,简单记录一下。