未定义条件符号时仍包含代码 [英] Code Still Being Included When Conditional Symbol Not Defined

查看:107
本文介绍了未定义条件符号时仍包含代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我一直在尝试通过使用Conditional属性来排除代码.我一直在使用的代码再简单不过了,如下所示:


Hi,

I have been experimenting with getting code to be excluded by use of the Conditional attribute. The code I have been using couldn''t be simpler, and is as follows:


class Program
{
	static void Main( string[] args )
	{
		CallFunction();
	}

	[Conditional("TEST_SYMBOL")]
	static void CallFunction()
	{
		int x = 1; 
		int y = 1; 
		_z = x - y;
		_z /= _z;
	}
		
	private static int _z = 0;
}



当我使用定义的TEST_SYMBOL构建和运行应用程序时,会出现预期的零除错误,而在未定义符号的情况下,我不会出现错误.到目前为止一切都很好.

但是,当我检查磁盘上的已编译程序集(定义和不定义符号)时,两者的字节数完全相同;当我用Reflector检查它们时,CallFunction()中的代码似乎在两个程序集中都存在.

我的理解是,Conditional属性不仅允许调用或不调用代码,而且如果未使用,也可以将其排除.否则,这只是其中一个程序集中不必要的代码膨胀.

我在这里想念什么吗?任何帮助将不胜感激.

最好的祝福,帕特里克



When I build and run the application with TEST_SYMBOL defined, I get the expected divide-by-zero error, and when the symbol is not defined, I get no error. So far so good.

But when I examine the compiled assemblies on disk (with and without the symbol defined), both are exactly the same number of bytes; and when I examine them with Reflector, the code in CallFunction() appears to be present in both assemblies.

My understanding was that the Conditional attribute allowed code, not just to be called or not called, but also to be excluded if unused. Otherwise, it is just unnecessary code bloat in one of the assemblies.

Am I missing something here? Any help would be very much appreciated.

Best wishes, Patrick

推荐答案

阅读本文: http://www.blackwasp.co.uk/ConditionalMethods.aspx [ ^ ]
我引用:
Read this article : http://www.blackwasp.co.uk/ConditionalMethods.aspx[^]
I quote :
"This key difference has benefits and drawbacks. The obvious drawback is that the compiled assembly will be larger than if the conditional method were not included. The main benefit is that the assembly can be shared between programs and libraries. Each of these may be compiled with different compiler symbols defined. This means that a single assembly can behave differently according to the program calling it. Another benefit is that the main code of the program is seen by some as more elegant without the #if and #endif conditions."



欢呼声



Cheers


如果您希望代码更小,则必须使用#if/#endif定义编译器指令.您在上面的代码中完成的操作仍将在编译的程序集中包含该方法,但只会将其公开给已定义了特定编译器定义的程序集(或代码).
If you want the code to be smaller, you have to use #if/#endif to define compiler directives. What you''ve done in the code above will still include the method in the compiled assembly, but will only expose it to assemblies (or code) that has the specific compiler definition defined.


这篇关于未定义条件符号时仍包含代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆