如何我得到属于自定义属性的财产? [英] How to I get the property belonging to a custom attribute?

查看:128
本文介绍了如何我得到属于自定义属性的财产?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to find the type of the property that a custom attribute is applied to from within the custom attribute.

例如:

[MyAttribute]
string MyProperty{get;set;}

由于MyAttribute的情况下,我怎么能得到一个myProperty的类型说明符?

Given the instance of MyAttribute, how could I get a Type descriptor for MyProperty?

在换句话说,我找System.Type.GetCustomAttributes相反()

In other words, I am looking for the opposite of System.Type.GetCustomAttributes()

推荐答案

本身一无所知的装饰着它的对象的属性。但是,你可以注入你retrive属性的时候这些信息。结果
在某些时候,你必须使用类似如下code要检索的属性。

The attribute itself knows nothing about the object that was decorated with it. But you could inject this information at the time you retrive the attribute.
At some point you have to retrieve the property using code similar to the following.

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;
}

这篇关于如何我得到属于自定义属性的财产?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆