好,反射API中的所有set方法都有相應的Get方法,所以從示例代碼可能是:
MyObject myObjectInstance = new MyObject();
System.Reflection.FieldInfo[] fieldInfo = myObjectType.GetFields();
string strValue = string.Empty;
int intValue = 0;
object objValue = null;
foreach (System.Reflection.FieldInfo info in fieldInfo)
{
switch (info.Name)
{
case "myStringField":
strValue = (string)info.GetValue(myObjectInstance);
break;
case "myIntField":
intValue = (int)info.GetValue(myObjectInstance);
break;
case "myObjectField":
objValue = info.GetValue(myObjectInstance);
break;
}
然而,這是一種低效的方式獲取/設置如果單個值你有很多的屬性,所以你可以使用getfield命令的方法,像這樣:
myType = myObjectInstance.GetType();
strValue = (string)myType.GetField("myStringField").GetValue(myObjectInstance);
intValue = (int)myType.GetField("myIntField").GetValue(myObjectInstance);
objValue = myType.GetField("myObjectField").GetValue(myObjectInstance);
還有一兩件事,反思是一個偉大的工具,但有一個代價。你的代碼不易維護(畢竟,你使用字符串作爲字段名稱)並且性能受到嚴重傷害。我的底線是儘可能避免反思,所以請先嚐試尋找替代解決方案。
你能顯示一些代碼嗎?反思可能不是這個工作的正確解決方案,你可能只需要一個InvokeRequired檢查。 – SWeko 2011-03-07 08:14:27