简体   繁体   中英

CallerMemberName and enums

From this answer:

https://stackoverflow.com/a/15738041/1250301

To this question:

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

You can use CallerMemberName to figure out which property an attribute is attached too. Which is pretty cool. Unfortunately, it doesn't seem to work with enums. For example:

https://dotnetfiddle.net/B69FCx

public static void Main()
{   
    var mi = typeof(MyEnum).GetMember("Value1");
    var attr = mi[0].GetCustomAttribute<FooAttribute>();

    mi = typeof(Bar).GetMember("SomeProp");
    attr = mi[0].GetCustomAttribute<FooAttribute>();
}

public class Bar
{
    [Foo]
    public string SomeProp { get; set; }
}

public class FooAttribute : Attribute
{
    public FooAttribute([CallerMemberName]string propName = null)
    {
        Console.WriteLine("Propname = " + propName);
    }
}

enum MyEnum  
{
    [Foo]
    Value1,
    [Foo]
    Value2
};

propName when you access it for a MyEnum is null, but for the class Bar it works as expected (ie it's SomeProp ). Is there a way to make this or something similar work for an enum? Or am I stuck with adding a property to FooAttribute and setting it when I add the property to the enum:

public class FooAttribute : Attribute
{
    public MyEnum AttachedTo { get; set; }
}

enum MyEnum  
{
    [Foo(AttachedTo = MyEnum.Value1)]
    Value1,
    [Foo(AttachedTo = MyEnum.Value2)]
    Value2
};

Which is tedious and has potential to be error prone.

CallerMemberName is not available for Assembly level or const members. Since an Enum value is essentially a const, you can't get that information. You will see the same behavior if you apply [Foo] to a public const member on class Bar .

As I was putting together a test, my inner voice kept screaming that I was doing something wrong. Having attributes on const's seems to be in opposition to the nature of decorators in general. I feel like you're getting into uncharted, 'Here there be monsters,' territory. You may want to rethink your design and consider a different path.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM