zhanbo说他的下一个Quiz会从他的随笔里出题,我就随便翻看了一下他的一些技术随笔,第一个就看到了Perf: Conditional("DEBUG")对性能的影响 这一篇。
我想不好的编码习惯再加上使用这个了ConditionalAttribute会影响到代码的正确性。利用MSDN里的例子举例并评论如下:
using System;
using System.Diagnostics;
class Class1
{
[STAThread]
static void Main(string[] args)
{
TextWriterTraceListener myWriter =
new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(myWriter);
Console.WriteLine("Console.WriteLine is always displayed");
int i=0;
Method1(++i); //使用++i会导致不可预料的结果,因为根据不同的编译条件,这一行可能不会出现在IL里
Method2(++i,++i);//上一行的有无会影响这一行里i的值
//Method1("abc"); 即使根据条件这一行不会出现在IL里,也会在编译时检查参数类型。这会导致编译错误,而不是执行错误。MSDN错误地写成了type-checked at run time
}
[Conditional("CONDITION1")]
public static void Method1(int a)
{
Debug.Write(String.Format("Method1 - DEBUG and CONDITION1 are specified:{0}\n", a));
Trace.Write("Method1 - TRACE and CONDITION1 are specified\n");
}
[Conditional("CONDITION1"), Conditional("CONDITION2")]
public static void Method2(int a,int b)
{
Debug.Write(String.Format("Method2 - DEBUG, CONDITION1 or CONDITION2 are specified:{0},{1}\n", a ,b));
}
}
D:\DOTNET>csc /target:exe /d:CONDITION2,DEBUG,TRACE /out:CASCS.exe CAS.cs
上面举例说明了,在分工合作进行开发的情况下,应该避免使用在调用函数的参数里更改变量。因为你的调用命令并不一定会被编译到最终的结果里。会发生看被调用方脸色而定的情况。我们使用 #if 或者 Debug.Write这样的命令都是可以预料结果的,而这个Attribute确让我们心神不定。
推而广之,这个Attribute使得调用方编写的任何函数调用都有可能不翼而飞。如果我写编码规范会禁止使用这个Attribute。
打印 | 张贴于 2004-06-14 15:20:00 | Tag:软件