gpt4 book ai didi

C# 通过属性反射设置属性值

转载 作者:IT王子 更新时间:2023-10-29 04:47:09 29 4
gpt4 key购买 nike

我正在尝试通过类属性上的属性构建一个对象,该属性在提供的数据行中指定一列作为属性的值,如下所示:

    [StoredDataValue("guid")]
public string Guid { get; protected set; }

[StoredDataValue("PrograGuid")]
public string ProgramGuid { get; protected set; }

在基础对象的 Build() 方法中,我将这些属性的属性值设置为

        MemberInfo info = GetType();
object[] properties = info.GetCustomAttributes(true);

然而,在这一点上,我意识到我知识的局限性。

首先,我似乎没有取回正确的属性。

既然我已经有了这些属性,我该如何通过反射来设置这些属性呢?我在做/想的事情根本上是错误的吗?

最佳答案

这里有几个独立的问题

  • typeof(MyClass).GetCustomAttributes(bool)(或 GetType().GetCustomAttributes(bool))返回类本身的属性,而不是成员的属性。您必须调用 typeof(MyClass).GetProperties() 来获取类中的属性列表,然后检查每个属性。

  • 获得属性后,我认为您应该使用 Attribute.GetCustomAttribute() 而不是 MemberInfo.GetGustomAttributes(),因为您确切地知道自己的属性是什么正在寻找。

这里有一小段代码片段可以帮助您开始:

PropertyInfo[] properties = typeof(MyClass).GetProperties();
foreach(PropertyInfo property in properties)
{
StoredDataValueAttribute attribute =
Attribute.GetCustomAttribute(property, typeof(StoredDataValueAttribute)) as StoredDataValueAttribute;

if (attribute != null) // This property has a StoredDataValueAttribute
{
property.SetValue(instanceOfMyClass, attribute.DataValue, null); // null means no indexes
}
}

编辑:不要忘记 Type.GetProperties() 默认只返回公共(public)属性。您还必须使用 Type.GetProperties(BindingFlags) 来获取其他类型的属性。

关于C# 通过属性反射设置属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/390594/

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