Adr*_*ore 10 c# reflection attributes
我需要在自定义属性中找到应用自定义属性的属性的类型.
例如:
[MyAttribute]
string MyProperty{get;set;}
Run Code Online (Sandbox Code Playgroud)
给定MyAttribute的实例,我怎样才能获得MyProperty的Type描述符?
换句话说,我正在寻找System.Type.GetCustomAttributes()的反面
Dan*_*ner 17
属性本身对用它装饰的对象一无所知.但是,您可以在重新检索属性时注入此信息.
在某些时候,您必须使用类似于以下的代码检索属性.
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;
}
Run Code Online (Sandbox Code Playgroud)