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配置的时候很是有用,简单记录一下。this

相关文章
相关标签/搜索