加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何获取属性属性的属性?

发布时间:2020-12-15 04:08:52 所属栏目:百科 来源:网络整理
导读:我需要在自定义属性中找到应用自定义属性的属性类型. 例如: [MyAttribute]string MyProperty{get;set;} 给定MyAttribute的实例,我如何获取MyProperty的类型描述符? 换句话说,我正在寻找与System.Type.GetCustomAttributes() 解决方法 属性本身对于用它进行
我需要在自定义属性中找到应用自定义属性的属性类型.

例如:

[MyAttribute]
string MyProperty{get;set;}

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

换句话说,我正在寻找与System.Type.GetCustomAttributes()

解决方法

属性本身对于用它进行装饰的对象一无所知.但您可以在您注销该属性时注入此信息.
在某些时候,您必须使用与以下代码类似的代码来检索该属性.
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;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读