How to get name of property which our attribute is set?

后端 未结 3 645
小鲜肉
小鲜肉 2020-12-15 03:34

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

class MyAtt : Attribute {
    string NameOfSettedProperty() {
        //How         


        
相关标签:
3条回答
  • 2020-12-15 03:50

    you can't do it within the attribute class itself. however, you can have a method that takes an object gets a list of that object's properties (if any) that use the attribute. use this API to implement that: http://msdn.microsoft.com/en-us/library/ms130869.aspx

    0 讨论(0)
  • 2020-12-15 03:53

    Using CallerMemberNameAttribute from .NET 4.5:

    public CustomAttribute([CallerMemberName] string propertyName = null)
    {
        // ...
    }
    
    0 讨论(0)
  • 2020-12-15 04:11

    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; }
    }
    
    0 讨论(0)
提交回复
热议问题