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

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

class MyAtt : Attribute { string NameOfSettedProperty() { //How do this? (Would be MyProp for example) } } class MyCls { [MyAtt] int MyProp { get { return 10; } } } 

属性是应用于类型成员,类型本身,方法参数或程序集的元数据。 为了能够访问元数据,您必须拥有原始成员本身的用户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; } } 

使用.NET 4.5中的CallerMemberNameAttribute :

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

你不能在属性类本身内做到这一点。 但是,您可以使用一个方法,该对象获取使用该属性的该对象属性(如果有)的列表。 使用此API实现: http : //msdn.microsoft.com/en-us/library/ms130869.aspx