4

我查看ConditionalAttribute声明,它是这样声明的:

我发现 JavaScript 代码是这样的:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method,
   AllowMultiple = true)]
public sealed class ConditionalAttribute : Attribute {
  //whatever
}

AttributeTargets.Class声称意味着属性可以应用于一个类。所以我尝试了这个:

[Conditional("DEBUG")]
class MyClass
{
}

但编译器发出以下错误

错误 CS1689:属性“System.Diagnostics.ConditionalAttribute”仅对方法或属性类有效

和 MSDN 说

此错误仅发生在 ConditionalAttribute 属性中。如消息所述,此属性只能用于方法或属性类。例如,尝试将此属性应用于类将生成此错误。

所以看起来有一个属性被声明为适用于一个类,但试图将它应用到一个类会导致编译错误。

这怎么可能?这是一些硬连线的特殊情况还是什么?

4

2 回答 2

6

Okay:

[Conditional("DEBUG")]
public void foo() { }

Okay too:

[Conditional("DEBUG")]
public class BarAttribute : Attribute { }

Not okay:

[Conditional("DEBUG")]
public class Baz { }

ConditionalAttribute can be applied to classes, but there's an additional restriction of the class being an attribute class.

If you want the whole class to be removed based on conditional define, then no, you can't to it. It's not supported. You'll have to mark each method individually.

于 2014-02-21T12:51:04.083 回答
4

Yes, ConditionalAttribute is a special case, being one of only a few attributes that are specifically handled directly by the compiler.

The compiler would have no well-defined behaviour in that case, so it chooses not to let you do it, to avoid confusion.

Of course, technically you could write a non-attribute class in MSIL that is marked with ConditionalAttribute, compile that with ilasm, and then reference it from a C# project - it would be interesting to know what the C# compiler does... I'm guessing it would do nothing special unless individual methods had the method too, since that is the scenario it targets.

于 2014-02-21T12:51:54.730 回答