使用条件属性 [Conditional("DEBUG")],而不使用#if DEBUG

ContractedBlock.gif ExpandedBlockStart.gif View Code
 
     
1 using System;
2 using System.Diagnostics;
3 namespace TraceFunctions
4 {
5 public class Trace
6 {
7 [Conditional( " DEBUG " )] // 条件属性
8 public static void Message( string traceMessage)
9 {
10 Console.WriteLine( " [TRACE] - " + traceMessage);
11 }
12 }
13 }
14
15 using System;
16 using TraceFunctions;
17
18 public class TraceClient
19 {
20 public static void Main( string [] args)
21 {
22 Trace.Message( " Main Starting " );
23
24 if (args.Length == 0 )
25 {
26 Console.WriteLine( " No arguments have been passed " );
27 }
28 else
29 {
30 for ( int i = 0 ; i < args.Length; i ++ )
31 {
32 Console.WriteLine( " Arg[{0}] is [{1}] " ,i,args[i]);
33 }
34 }
35
36 Trace.Message( " Main Ending " );
37 }
38 }

如果使用#if DEBUG,则为

ContractedBlock.gif ExpandedBlockStart.gif View Code
 
     
1 using System;
2 using System.Diagnostics;
3 namespace TraceFunctions
4 {
5 public class Trace
6 {
7 public static void Message( string traceMessage)
8 {
9 #if DEBUG
10 Console.WriteLine( " [TRACE] - " + traceMessage);
11 #endif
12 }
13 }
14 }
15 using System;
16 using TraceFunctions;
17
18 public class TraceClient
19 {
20 public static void Main( string [] args)
21 {
22 Trace.Message( " Main Starting " );
23
24 if (args.Length == 0 )
25 {
26 Console.WriteLine( " No arguments have been passed " );
27 }
28 else
29 {
30 for ( int i = 0 ; i < args.Length; i ++ )
31 {
32 Console.WriteLine( " Arg[{0}] is [{1}] " ,i,args[i]);
33 }
34 }
35
36 Trace.Message( " Main Ending " );
37 }
38 }
在DEGUB下和之前的是一样的,但在Release下, public static void Message(string traceMessage)函数为空函数,此时它什么也不做,但却会被调用,增大了开销

转载于:https://www.cnblogs.com/21vicky21/archive/2011/04/07/2007481.html

你可能感兴趣的:(使用条件属性 [Conditional("DEBUG")],而不使用#if DEBUG)