【发布时间】:2016-06-09 02:29:18
【问题描述】:
在 C# 中是否可以对属性进行限制,使其只能在具有另一个属性的类中的方法上?
[MyClassAttribute]
class Foo
{
[MyMethodAttribute]
public string Bar()
}
其中“MyMethodAttribute”只能在具有“MyClassAttribute”的类中。
这可能吗?如果可以,怎么做?
【问题讨论】:
-
我怀疑这是可能的,属性本身什么都不做。
-
我不知道实现这一点的编译时方法。但是,在
MyMethodAttributector 中,您可以通过反射检查托管MyMethodAttribute的类上是否存在必需的属性。 -
您可以编写一个 Roslyn 分析器,在编译时对此进行验证,如果违反此规则则显示错误。
标签: c# attributes restriction