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

43

我打算不传递任何参数给属性,这种做法可行吗?

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

class MyCls {
    [MyAtt]
    int MyProp { get { return 10; } }
}
3个回答

182

使用 .NET 4.5 中的 CallerMemberNameAttribute

public CustomAttribute([CallerMemberName] string propertyName = null)
{
    // ...
}

1
太棒了。它保存了一个属性的参数,我将用它来装饰整个项目中的属性。 - Ellesedil
2
很遗憾,我正在寻找这个但是不能与枚举一起使用 - Kapé

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

9
谢谢,我知道可以通过传递属性名称来解决这个问题,但我打算不传递属性名称来解决。根据你的回答,这是不可能的。 - Sadegh
不可能,属性没有传递有关其所附加到的成员的信息。如果“Attribute”实例被传递用于创建它的“ICustomAttributeProvider”,那将非常方便,但遗憾的是这并不是情况。 - Matthew Abbott
4
此评论已过时。如果使用.NET 4.5,请参见下文。 - Jon Barker

0

好的,我知道有很多种方法(像你的方法),但是这些都不适用于我的情况。 - Sadegh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接