CallerMemberName和枚举 [英] CallerMemberName and enums

查看:126
本文介绍了CallerMemberName和枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从这个答案中:

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

对于此问题:

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

您可以使用 CallerMemberName 来确定附加属性的属性。哪个很酷不幸的是,它似乎不适用于枚举。例如:

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 code> MyEnum 为null,但是对于类 Bar 它可以按预期工作(即它的 SomeProp )。有没有办法使这个或类似的工作为枚举?或者我将卡添加到 FooAttribute 中的属性,并在将属性添加到枚举时进行设置:

propName when you access it for a MyEnum is null, but for the class Bar it works as expected (i.e. 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 不适用于程序集级别或 const 成员。因为枚举值本质上是一个const,所以你不能得到这个信息。如果您将 [Foo] 应用于中的 public const 成员,您将看到相同的行为课堂吧

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.

当我在一起测试时,内心的声音一直在尖叫着说我做错了事情。对const的属性似乎与一般的装饰者的性质相反。我觉得你进入未知的地方,这里有怪物领土。您可能想重新考虑您的设计,并考虑不同的路径。

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.

这篇关于CallerMemberName和枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆