gpt4 book ai didi

c# - 通过属性值获取属性名

转载 作者:太空宇宙 更新时间:2023-11-03 16:30:47 24 4
gpt4 key购买 nike

美好的一天,如果我有该属性的自定义属性值,我该如何获取类的属性名称?当然还有自定义属性名称。

最佳答案

通过自定义属性获取属性名:

    public static string[] GetPropertyNameByCustomAttribute
<ClassToAnalyse, AttributeTypeToFind>
(
Func<AttributeTypeToFind, bool> attributePredicate
)
where AttributeTypeToFind : Attribute
{
if (attributePredicate == null)
{
throw new ArgumentNullException("attributePredicate");
}
else
{
List<string> propertyNames = new List<string>();

foreach
(
PropertyInfo propertyInfo in typeof(ClassToAnalyse).GetProperties()
)
{
if
(
propertyInfo.GetCustomAttributes
(
typeof(AttributeTypeToFind), true
).Any
(
currentAttribute =>
attributePredicate((AttributeTypeToFind)currentAttribute)
)
)
{
propertyNames.Add(propertyInfo.Name);
}
}

return propertyNames.ToArray();
}
}

测试夹具:

public class FooAttribute : Attribute
{
public String Description { get; set; }
}

class FooClass
{
private int fooProperty = 42;

[Foo(Description="Foo attribute description")]
public int FooProperty
{
get
{
return this.fooProperty;
}
}

}

测试用例:

// It will return "FooProperty"
GetPropertyNameByCustomAttribute<FooClass, FooAttribute>
(
attribute => attribute.Description == "Foo attribute description"
);


// It will return an empty array
GetPropertyNameByCustomAttribute<FooClass, FooAttribute>
(
attribute => attribute.Description == "Bar attribute description"
);

关于c# - 通过属性值获取属性名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10835519/

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