如何获取属性设置的属性名称?

Sad*_*egh 33 c# reflection attributes

我将在不传递属性的任何参数的情况下执行此操作!可能吗?

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

class MyCls {
    [MyAtt]
    int MyProp { get { return 10; } }
}
Run Code Online (Sandbox Code Playgroud)

tuk*_*aef 143

使用.NET 4.5中的CallerMemberNameAttribute:

public CustomAttribute([CallerMemberName] string propertyName = null)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案,谢谢你! (10认同)
  • 正在寻找这个,但不幸的是[使用枚举](http://stackoverflow.com/q/28094024/465942)不起作用.. (2认同)

Mat*_*ott 3

属性是应用于类型成员、类型本身、方法参数或程序集的元数据。为了使您能够访问元数据,您必须拥有原始成员本身的用户GetCustomAttributes等,即您的TypePropertyInfoFieldInfo的实例。

在你的例子中,我实际上会将属性的名称传递给属性本身:

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; }
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我知道这可以通过传递属性名称来解决,我将在不传递属性名称的情况下执行此操作。所以根据你的回答,这是不可能的。 (9认同)
  • 此评论已过时。如果使用 .NET 4.5,请参见下文 (4认同)