如果这在某处被覆盖,我深表歉意。发帖前我做了研究!
好的,所以问题...我正在使用 GetType( ).GetProperties,但它没有返回简单的实例字段,它们没有获取/设置...所以我使用了 .GetFields,它可以找到它们,但我想获得一个简单的单个对象来获取/设置一个值而不在字段和属性之间翻转......这可能吗?
我当前的代码适用于 PropertyInfo,效果很好,但这不适用于我猜的字段?
[编辑] 这是我想出的解决方案,效果很好。感谢大家....
// some logic borrowed from James Newton-King, http://www.newtonsoft.com
public static void SetValue(this MemberInfo member, object property, object value)
{
if (member.MemberType == MemberTypes.Property)
((PropertyInfo)member).SetValue(property, value, null);
else if (member.MemberType == MemberTypes.Field)
((FieldInfo)member).SetValue(property, value);
else
throw new Exception("Property must be of type FieldInfo or PropertyInfo");
}
public static object GetValue(this MemberInfo member, object property)
{
if (member.MemberType == MemberTypes.Property)
return ((PropertyInfo)member).GetValue(property, null);
else if (member.MemberType == MemberTypes.Field)
return ((FieldInfo)member).GetValue(property);
else
throw new Exception("Property must be of type FieldInfo or PropertyInfo");
}
public static Type GetType(this MemberInfo member)
{
switch (member.MemberType)
{
case MemberTypes.Field:
return ((FieldInfo)member).FieldType;
case MemberTypes.Property:
return ((PropertyInfo)member).PropertyType;
case MemberTypes.Event:
return ((EventInfo)member).EventHandlerType;
default:
throw new ArgumentException("MemberInfo must be if type FieldInfo, PropertyInfo or EventInfo", "member");
}
}