gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:22:30 26 4
gpt4 key购买 nike

使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com