从这个答案中:
https://stackoverflow.com/a/15738041/1250301
关于这个问题:
How to get name of property which our attribute is set?
您也可以使用CallerMemberName来确定属性附加了哪个属性。这是相当酷的。不幸的是,它似乎不能与枚举一起工作。例如:
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
};当您为MyEnum访问它时,propName是空的,但对于Bar类,它的工作方式是预期的(即它是SomeProp)。有没有办法让这个或类似的东西对枚举起作用?或者,当我将属性添加到枚举时,我是否不得不向FooAttribute添加属性并对其进行设置:
public class FooAttribute : Attribute
{
public MyEnum AttachedTo { get; set; }
}
enum MyEnum
{
[Foo(AttachedTo = MyEnum.Value1)]
Value1,
[Foo(AttachedTo = MyEnum.Value2)]
Value2
};这是单调乏味的,并且有可能容易出错。
发布于 2015-01-23 01:28:49
对于程序集级或const成员,CallerMemberName不可用。由于枚举值本质上是一个常量,因此您无法获取该信息。如果将[Foo]应用于class Bar上的public const成员,您将看到相同的行为。
当我在做一个测试时,我内心的声音一直在尖叫,说我做错了什么。在const上拥有属性似乎与装饰器的本质大体相反。我觉得你进入了一个未知的领域,“这里有怪物”。您可能希望重新考虑您的设计,并考虑一条不同的路径。
https://stackoverflow.com/questions/28094024
复制相似问题