如何获得,我们的属性被设置的属性名? [英] How to get name of property which our attribute is set?

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

问题描述

我要做到这一点不传递任何参数,属性!这可能吗?

 类迈亚特:属性{
    串NameOfSettedProperty(){
        //如何做到这一点? (会MyProp为例)
    }
}类MyCls {
    [迈亚特]
    INT MyProp {{返回10; }}
}


解决方案

属性应用于一个类型,该类型本身,方法参数或议会成员的元数据。因为你有机会获得元数据,你必须有原成员本身用户 GetCustomAttributes 等,即你的实例键入的PropertyInfo 字段信息等。

在你的情况,我真的传递属性的名称属性本身:

 公共CustomAttribute:属性
{
  公共CustomAttribute(字符串propertyName的)
  {
    this.PropertyName = propertyName的;
  }  公共字符串属性名{获得;私人集; }
}公共类MyClass的
{
  [自定义(myProperty的)]
  公众诠释myProperty的{搞定;组; }
}

I'm going to do this without passing any parameter to attribute! Is it possible?

class MyAtt : Attribute {
    string NameOfSettedProperty() {
        //How do this? (Would be MyProp for example)
    }
}

class MyCls {
    [MyAtt]
    int MyProp { get { return 10; } }
}

解决方案

Attributes are metadata applied to members of a type, the type itself, method parameters, or the assembly. For you to have access to the metadata, you must have had the original member itself to user GetCustomAttributes etc, i.e. your instance of Type, PropertyInfo, FieldInfo etc.

In your case, I would actually pass the name of the property to the attribute itself:

public CustomAttribute : Attribute
{
  public CustomAttribute(string propertyName)
  {
    this.PropertyName = propertyName;
  }

  public string PropertyName { get; private set; }
}

public class MyClass
{
  [Custom("MyProperty")]
  public int MyProperty { get; set; }
}

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

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