这实际上取决于您要做什么:
我个人根据情况使用两种:
我使用它是为了不必稍后在发行过程中回去编辑我的代码,但是在调试过程中,我想确保自己没有打错任何文字。尝试在INotifyPropertyChanged东西中使用属性名称时,此函数检查是否正确键入了属性名称。
[Conditional("DEBUG")]
[DebuggerStepThrough]
protected void VerifyPropertyName(String propertyName)
{
if (TypeDescriptor.GetProperties(this)[propertyName] == null)
Debug.Fail(String.Format("Invalid property name. Type: {0}, Name: {1}",
GetType(), propertyName));
}
#if DEBUG
除非您愿意以相同的方式包装对该函数的每个调用,否则您确实不想使用该函数#if DEBUG
:
#if DEBUG
public void DoSomething() { }
#endif
public void Foo()
{
#if DEBUG
DoSomething(); //This works, but looks FUGLY
#endif
}
与:
[Conditional("DEBUG")]
public void DoSomething() { }
public void Foo()
{
DoSomething(); //Code compiles and is cleaner, DoSomething always
//exists, however this is only called during DEBUG.
}
我在尝试为WCF通信设置不同的绑定时使用它。
#if DEBUG
public const String ENDPOINT = "Localhost";
#else
public const String ENDPOINT = "BasicHttpBinding";
#endif
在第一个示例中,所有代码都存在,但除非打开DEBUG,否则它将被忽略。在第二个示例中,取决于是否设置了DEBUG,将const ENDPOINT设置为“ Localhost”或“ BasicHttpBinding”。
更新:我正在更新此答案以阐明重要且棘手的问题。如果选择使用ConditionalAttribute
,请记住,在编译过程中会忽略调用,而 。那是:
MyLibrary.dll
[Conditional("DEBUG")]
public void A()
{
Console.WriteLine("A");
B();
}
[Conditional("DEBUG")]
public void B()
{
Console.WriteLine("B");
}
当针对发布模式(即,没有DEBUG符号)编译该库时,即使其中包含对to 的调用,也会永久忽略B()
from内A()
的调用,A()
因为在调用程序集中定义了DEBUG。