c#泛型类无法获取属性值
使用c#反射得到&设置通用对象内的通用字段的值.但我找不到任何方法来获得这些字段的属性值.下面的代码示例:
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; } 问题 itemField.GetType()始终返回System.Reflection.RtFieldInfo类型,但不返回Foo类型. 我已经尝试过使用itemField.FieldType.GetProperty(“IsUpdated”),它在返回正确的属性时起作用.但抛出错误“对象与目标类型不匹配”.每当调用GetValue()方法时 如果得到任何人的帮助,我们将非常感激! 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"); } } 解决方法
让我们一次解开这一件事:
var isUpdatedProp = itemField.GetType().GetProperty("IsUpdated"); 你永远不需要在成员上使用.GetType();你想要.FieldType或.PropertyType(对于属性).并且名字很棒: var isUpdatedProp = itemField.FieldType.GetProperty(nameof(Foo<string>.IsUpdated)); (这里的字符串是假的) 然后: isUpdated = isUpdatedProp.GetValue(itemField,null).ToString(); itemField不是你的对象 – 这就是该对象上itemField的值给你的东西.所以通过;如果可能的话,将结果视为布尔值: var isUpdated = false; object foo = itemField.GetValue(itemList); ... isUpdated = (bool)isUpdatedProp.GetValue(foo,null); 最后: if (isUpdated == "false") isUpdatedProp.SetValue(itemField,"true"); 对象再次是itemList,属性不是字符串 if (!isUpdated) isUpdatedProp.SetValue(foo,true); 如果你制作Foo< T>会更容易. :IFoo,其中IFoo是非通用接口: interface IFoo { bool IsUpdated {get; set; } } 然后它变成: var foo = (IFoo)itemField.GetValue(itemList); if(!foo.IsUpdated) foo.IsUpdated = true; 最后,请注意,如果您没有为它们指定任何内容,FirstName和LastName将为null. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |