好,反射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