我正在使用腰带和吊带类型检查潜在的空对象问题。不过,Resharper 的表现并不好。在调试版本中,它将 if (button != null)
检查标记为始终为真,并在边栏中放置一个警告标记。在发布版本中,它将 Debug.Assert
隐藏为从未使用过的代码,但至少这次它足够聪明,不会弄乱侧边栏。
我不想全局禁用 always true/false resharper 警告,因为它可能表明代码中存在问题。同时,每次我进行检查时都必须使用 ReSharper disable/restore ConditionIsAlwaysTrueOrFalse
注释来打乱我的代码,这很丑陋。
ReSharper 5.1 中是否有一个选项可以禁用构建类型的偶然行为,以便在调试构建中不标记 if,如果 Assert
不存在,则不会阻止显示警告?
//This should always work unless the columns are fiddled with.
LinkButton button = e.Row.Cells[5].FindControl( "linkButtonName" ) as LinkButton;
//if this isn't the case in a debug build have VS throw an error in the devs face
Debug.Assert(button != null);
//Don't let anything go boom in production if an error isn't caught in dev
if (button != null)
button.Visible = ( schedule.CreatedBy == Authentification.GetLoggedInUser() );
最佳答案
不确定我是否同意该设计,但考虑到您想要完成的任务,请尝试以下操作。
- 从 http://research.microsoft.com/en-us/projects/contracts/ 安装代码契约(Contract)
- 将您的 Debug.Asserts 重写为 Contract.Assert
- 然后更改您的项目属性以仅检查调试版本中的契约(Contract)。
所以看来您的问题最容易通过将 debug.assert 替换为以下内容来解决:
//Throw an error only if there is a problem with
Contract.Assert(button!=null);
但是,我可能会更改设计,使使用链接按钮完成的工作成为以下方法,假设您可能有其他事情正在使用链接按钮进行。
所以你上面的代码是:
public void MyMethod(EventArgs e)
{
var button = e.Row.Cells[5].FindControl("linkButtonName") as LinkButton;
SetButtonVisibility(button);
}
public void SetButtonVisibility(LinkButton button)
{
//The button is never null so its a contract
Contract.Requires<ArgumentNullException>(button != null);
button.Visible = (schedule.CreatedBy == Authentification.GetLoggedInUser());
}
希望对您有所帮助。
关于c# - 禁用依赖于构建类型的 resharper 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8158160/