c#泛型类无法获取属性值

标签 c# object generics reflection field

使用 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() 方法时都会抛出错误 “对象与目标类型不匹配。” 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");
            }
        }

最佳答案

让我们一次打开一个东西:

var isUpdatedProp = itemField.GetType().GetProperty("IsUpdated");

你应该永远需要使用.GetType()在成员上;你想要.FieldType.PropertyType (对于属性)。和 nameof很棒:

var isUpdatedProp = itemField.FieldType.GetProperty(nameof(Foo<string>.IsUpdated));

(string 这是一个假人)

然后:

 isUpdated = isUpdatedProp.GetValue(itemField, null).ToString();

这不是 itemField那就是你的对象——这就是 itemField 的值在那个对象上给你。所以把它传进去;并将结果视为 bool 值,如果可能的话:

var isUpdated = false;
object foo = itemField.GetValue(itemList);
...
isUpdated = (bool)isUpdatedProp.GetValue(foo, null);

最后:

if (isUpdated == "false") isUpdatedProp.SetValue(itemField, "true");

再一次,对象是itemList ,并且该属性不是 string

if (!isUpdated) isUpdatedProp.SetValue(foo, true);

如果你做 Foo<T> : IFoo 会更容易其中 IFoo是一个非通用接口(interface):

interface IFoo { bool IsUpdated {get; set; } }

然后变成:

var foo = (IFoo)itemField.GetValue(itemList);
if(!foo.IsUpdated) foo.IsUpdated = true;

最后,请注意 FirstNameLastName 将是空的如果你没有给他们分配任何东西。

关于c#泛型类无法获取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49278817/

相关文章:

c# - Java 的 Class<X> 类型在 C# 中的等价物是什么?

c# - 从 c# 到 Access DB 的 INSERT STATEMENT 中的语法错误

c# - 如何在除ffmpeg之外的C# windows窗体中合并音频和视频

c# - 为什么 Fakes 不能从预建的 Fakes 项目中正确引用 Fakes dll?

c# - 如何以编程方式搜索 C# DropDownList

object - TCL:使用 ActiveTcl 8.6 将对象作为过程的参数传递

c# - 如何编写 C# 方法来返回基于枚举参数的 Func<T> ?

javascript - Vue.js 导入对象

python - 如何从作为参数传递的类初始化对象

java - 如何从java中的方法返回泛型类型