gpt4 book ai didi

c# - 如何获取属于自定义属性的属性?

转载 作者:可可西里 更新时间:2023-11-01 08:57:58 25 4
gpt4 key购买 nike

我需要从自定义属性中找到应用了自定义属性的属性的类型。

例如:

[MyAttribute]
string MyProperty{get;set;}

给定 MyAttribute 的实例,我如何获得 MyProperty 的类型描述符?

换句话说,我正在寻找 System.Type.GetCustomAttributes() 的对立面

最佳答案

属性本身对用它装饰的对象一无所知。但是您可以在检索属性时注入(inject)此信息。
在某些时候,您必须使用类似于以下的代码来检索属性。

PropertyInfo propertyInfo = typeof(MyType).GetProperty("MyProperty");

Object[] attribute = propertyInfo.GetCustomAttributes(typeof(MyAttribute), true);

if (attribute.Length > 0)
{
MyAttribute myAttribute = (MyAttribute) attributes[0];

// Inject the type of the property.
myAttribute.PropertyType = propertyInfo.PropertyType;

// Or inject the complete property info.
myAttribute.PropertyInfo = propertyInfo;
}

关于c# - 如何获取属于自定义属性的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/916904/

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