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

相關文章
相關標籤/搜索