使用C#反射来获取和设置泛型对象中的泛型字段的值。但我找不到任何方法来获取这些字段的属性值。以下是示例代码:
问题: 在 (*) 行出现了“null”项。
itemField.GetType() 总是返回 System.Reflection.RtFieldInfo 类型,而不是 Foo 类型。
我已经尝试使用 itemField.FieldType.GetProperty("IsUpdated"),它可以返回正确的属性。但是每当调用 GetValue() 方法时,就会抛出一个错误 "Object does not match target type.",如下所示: itemField.FieldType.GetProperty("IsUpdated").GetValue(itemField, null)
非常感谢任何人提供帮助!
public class Foo<T>
{
public bool IsUpdated { get; set; }
}
public abstract class ValueObjec<T>
{
public string InnerValue { get; set; }
}
public class ItemList: ValueObject<ItemList>
{
public Foo<string> FirstName;
public Foo<string> LastName;
}
问题: 在 (*) 行出现了“null”项。
itemField.GetType() 总是返回 System.Reflection.RtFieldInfo 类型,而不是 Foo 类型。
我已经尝试使用 itemField.FieldType.GetProperty("IsUpdated"),它可以返回正确的属性。但是每当调用 GetValue() 方法时,就会抛出一个错误 "Object does not match target type.",如下所示: itemField.FieldType.GetProperty("IsUpdated").GetValue(itemField, null)
非常感谢任何人提供帮助!
var itemList = new ItemList();
foreach (var itemField in itemList.GetType().GetFields())
{
var isUpdated = "false";
var isUpdatedProp = itemField.GetType().GetProperty("IsUpdated"); // (*) return null from here
if (isUpdatedProp != null)
{
isUpdated = isUpdatedProp.GetValue(itemField, null).ToString();
if (isUpdated == "false") isUpdatedProp.SetValue(itemField, "true");
}
}
foreach (var itemField in itemList.GetType().GetFields())
{
var isUpdated = "false";
var isUpdatedProp = itemField.FieldType.GetProperty("IsUpdated");
if (isUpdatedProp != null)
{
isUpdated = isUpdatedProp.GetValue(itemField, null).ToString(); (*) // throw error "Object does not match target type"
if (isUpdated == "false") isUpdatedProp.SetValue(itemField, "true");
}
}
foreach ( var itemList ...
中有个打字错误,应该是foreach ( var itemField ...
。 - FildorFlattenHierarchy
绑定标志,否则继承的属性不会被GetProperty
返回:BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy
。 - user47589