java if debug_#if DEBUG vs.条件(“DEBUG”)

这真的取决于你的目标:

#if DEBUG :此处的代码在发布时甚至不会达到IL .

[Conditional("DEBUG")] :此代码将到达IL,但是除非在编译调用者时设置了DEBUG,否则将省略对该方法的调用 .

我根据具体情况个人使用:

Conditional("DEBUG") Example: 我使用这个,所以我不做任何拼写错误 . 当我在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.

}

#if DEBUG example: 我在尝试为WCF通信设置不同的绑定时使用它 .

#if DEBUG

public const String ENDPOINT = "Localhost";

#else

public const String ENDPOINT = "BasicHttpBinding";

#endif

在第一个示例中,代码全部存在,但只是被忽略,除非打开DEBUG . 在第二个示例中,const ENDPOINT设置为“Localhost”或“BasicHttpBinding”,具体取决于是否设置了DEBUG .

更新:我正在更新这个答案,以澄清一个重要且棘手的问题 . 如果选择使用 ConditionalAttribute ,请记住在编译期间省略了调用,并且 not runtime . 那是:

MyLibrary.dll

[Conditional("DEBUG")]

public void A()

{

Console.WriteLine("A");

B();

}

[Conditional("DEBUG")]

public void B()

{

Console.WriteLine("B");

}

当库是针对释放模式编译的(即没有DEBUG符号)时,即使调用 A() ,因为在调用程序集中定义了DEBUG,它将永远从 A() 内省略 B() 的调用 .

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值