有没有办法将属性标记为条件
Is there a way to mark an attribute as conditional
所以,我正在处理一些属性,然后我意识到拥有一个以我是在调试还是发布中构建为条件的属性可能对我有帮助。
原来我搜索google或堆栈溢出都找不到我要找的东西。有一个名为 [Conditional] 的属性,还有一个 [DebuggerDisplay],但我找不到将属性本身设置为条件的属性。
下面link解释了[Conditional] vs #if Debug
#if DEBUG vs. Conditional("DEBUG")
我正在寻找的更接近 only preferred in attribute 形式。
#if DEBUG
[SomeAttribute(...)]
#endif
我意识到我可以执行 #define 然后使用正确的符号,这样我就不必再进行 #if 调试了,但我觉得应该有一个我不知道的属性标志。
不,我不这么认为。
如果你想包含有条件编译的代码,你必须使用这些 #if, #else, #elif #endif
编译器指令,没有它就没有绝对的方法。
您甚至可以在您的属性 class 上使用 ConditionalAttribute
,但它会被编译到程序集中,但稍后会被 JIT
编译器优化。
这应该可以帮助您理解:How does the Conditional attribute work? and Omitting code: Any difference between Conditional Attribute and pre-processing directive?
这在一定程度上取决于您要实现的目标。
如果您是 SomeAttribute
的作者,并且您希望 所有 应用该属性都是有条件的,那么您可以应用 Conditional
属性关于类型声明本身:
[Conditional("DEBUG")]
[System.AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class SomeAttribute : Attribute
{
...
如果您没有 SomeAttribute
的源代码,或者您不希望它是全有或全无,那么预处理器语句就是内置的所有内容。
所以,我正在处理一些属性,然后我意识到拥有一个以我是在调试还是发布中构建为条件的属性可能对我有帮助。
原来我搜索google或堆栈溢出都找不到我要找的东西。有一个名为 [Conditional] 的属性,还有一个 [DebuggerDisplay],但我找不到将属性本身设置为条件的属性。
下面link解释了[Conditional] vs #if Debug #if DEBUG vs. Conditional("DEBUG")
我正在寻找的更接近 only preferred in attribute 形式。
#if DEBUG
[SomeAttribute(...)]
#endif
我意识到我可以执行 #define 然后使用正确的符号,这样我就不必再进行 #if 调试了,但我觉得应该有一个我不知道的属性标志。
不,我不这么认为。
如果你想包含有条件编译的代码,你必须使用这些 #if, #else, #elif #endif
编译器指令,没有它就没有绝对的方法。
您甚至可以在您的属性 class 上使用 ConditionalAttribute
,但它会被编译到程序集中,但稍后会被 JIT
编译器优化。
这应该可以帮助您理解:How does the Conditional attribute work? and Omitting code: Any difference between Conditional Attribute and pre-processing directive?
这在一定程度上取决于您要实现的目标。
如果您是 SomeAttribute
的作者,并且您希望 所有 应用该属性都是有条件的,那么您可以应用 Conditional
属性关于类型声明本身:
[Conditional("DEBUG")]
[System.AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public class SomeAttribute : Attribute
{
...
如果您没有 SomeAttribute
的源代码,或者您不希望它是全有或全无,那么预处理器语句就是内置的所有内容。