反射技術給類賦值的好處就是可以簡化代碼,封裝的好處就顯而易見了。最直接的用途就是用在在顯示配置文件的時候,個人習慣性做法是做一個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配置的時候非常有用,簡單記錄一下。