禁用依赖于构建类型的resharper警告

Dan*_*ely 17 c# resharper resharper-5.1

我正在使用腰带和吊带类型检查潜在的空对象问题.虽然Resharper打得不好.在调试版本中,它将if (button != null)检查标记为始终为true,并在侧栏中放置警告标记.在发布版本中,它会遮盖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() );
Run Code Online (Sandbox Code Playgroud)

小智 2

不确定我是否同意该设计,但鉴于您想要完成的任务,请尝试以下操作。

  1. 从http://research.microsoft.com/en-us/projects/contracts/安装代码合同
  2. 将 Debug.Asserts 重写为 Contract.Assert
  3. 然后更改项目属性以仅检查调试版本中的合同。

因此,通过将 debug.assert 替换为以下内容,您的问题似乎最容易解决:

  //Throw an error only if there is a problem with 
  Contract.Assert(button!=null);
Run Code Online (Sandbox Code Playgroud)

但是,我可能会更改设计,使使用链接按钮完成的工作成为以下方法,假设您可能还有其他与链接按钮有关的事情。

所以你上面的代码将是:

    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());

    }
Run Code Online (Sandbox Code Playgroud)

希望有帮助。