What does ConditionalAttribute on an Attribute do?

末鹿安然 提交于 2019-12-22 12:07:48

问题


I know what ConditionalAttribute does.

The docs say it can also be applied to a class, if it's derived from Attribute:

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

But how does that custom attribute behave? (Is it stripped out of a release build?)


回答1:


@RicardoPontual's comment gave me an idea.

I did this:

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

[Foo]
public class Bar { }

I compiled in debug mode, and loaded the DLL in ILSpy (it's a disassembler). This is what I found, as expected:

[Foo]
public class Bar { }

Then I compiled in release mode, and loaded that DLL in ILSpy. This is what I found:

public class Bar { }

The Bar class was not decorated this time!

So, the answer is that when you decorate some custom attribute with Conditional, then that attribute itself becomes conditional in the same way.

That's the behavior I wanted. I initially thought to derive from ConditionalAttribute, but it's sealed. Instead you need to decorate your custom attribute.



来源:https://stackoverflow.com/questions/38982444/what-does-conditionalattribute-on-an-attribute-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!