ReSharper:如何删除“可能的“System.NullReferenceException””警告

发布于 2024-10-06 21:46:45 字数 1093 浏览 0 评论 0原文

这是一段代码:

IUser user = managerUser.GetUserById(UserId);
if ( user==null ) 
    throw new Exception(...);

Quote quote = new Quote(user.FullName, user.Email);

这里一切都很好。但是,如果我将“if”行替换为以下行:

ComponentException<MyUserManagerException>.FailIfTrue(user == null, "Can't find user with Id=" + UserId);

其中函数实现如下:

public abstract class ComponentException<T> : ComponentException
        where T : ComponentException, new()
{
    public static void FailIfTrue(bool expression, string message)
    {
        if (expression)
        {
            T t = new T();
            t.SetErrorMessage(message);
            throw t;
        }
    }
    //...
}

然后 ReSharper 会生成一个警告:可能的“System.NullReferenceException”指向“用户”对象的第一次使用。

Q1.为什么会产生这样的异常?据我所知,如果 user==null 则会生成异常,并且执行将永远不会到达使用点。

Q2。如何删除该警告?请注意: 1.我不想用注释来抑制这个警告(我会有很多类似的片段,并且不想将我的源代码转换为“注释垃圾”); 2.我不想更改ReSharper设置来将此问题从警告更改为“提示”的“建议”。

谢谢。

欢迎任何想法!

PS 我正在使用 resharper 5.1、MVSV 2008、C#

Here is a piece of code:

IUser user = managerUser.GetUserById(UserId);
if ( user==null ) 
    throw new Exception(...);

Quote quote = new Quote(user.FullName, user.Email);

Everything is fine here. But if I replace "if" line with the following one:

ComponentException<MyUserManagerException>.FailIfTrue(user == null, "Can't find user with Id=" + UserId);

where function implementation is following:

public abstract class ComponentException<T> : ComponentException
        where T : ComponentException, new()
{
    public static void FailIfTrue(bool expression, string message)
    {
        if (expression)
        {
            T t = new T();
            t.SetErrorMessage(message);
            throw t;
        }
    }
    //...
}

Then ReSharper generates me a warning: Possible 'System.NullReferenceException' pointing on 1st usage of 'user' object.

Q1. Why it generates such exception? As far as I see if user==null then exception will be generated and execution will never reach the usage point.

Q2. How to remove that warning? Please note:
1. I don't want to suppress this warning with comments (I will have a lot of similar pieces and don't want to transform my source code in 'commented garbage);
2. I don't want to changes ReSharper settings to change this problem from warning to 'suggestion' of 'hint'.

Thanks.

Any thoughts are welcome!

P.S. I am using resharper 5.1, MVSV 2008, C#

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

暮凉 2024-10-13 21:46:45

Resharper 只查看当前方法进行分析,不会递归分析您调用的其他方法。

不过,您可以稍微指导 Resharper 并为其提供有关某些方法的元信息。例如,它知道“Assert.IsNotNull(a)”,并将在分析时考虑该信息。可以为 Resharper 制作一个外部注释文件,并为其提供有关某个库的额外信息,以使其分析更好。也许这可以提供解决您问题的方法。

更多信息请访问此处

可以在 此处找到显示它如何用于 Microsoft.Contracts 库的示例

Resharper only looks at the current method for its analysis, and does not recursively analyse other methods you call.

You can however direct Resharper a bit and give it meta-information about certain methods. It knows for example about "Assert.IsNotNull(a)", and will take that information into account for the analysis. It is possible to make an external annotations file for Resharper and give it extra information about a certain library to make its analysis better. Maybe this might offer a way to solve your problem.

More information can be found here.

An example showing how it's used for the library Microsoft.Contracts can be found here.

江南月 2024-10-13 21:46:45

旧帖子中的新答案...

这里是我的代码的一个小示例,涉及如何通过 ContractAnnotation 与 Resharper 使用 CodeContract:

    [ContractAnnotation("value:null=>true")]
    public static bool IsNullOrEmpty(this string value)
    {
        return string.IsNullOrEmpty(value);
    }

这非常简单...如果您在木头中找到面包屑。您也可以检查其他情况。

祝你今天过得愉快

A new answer in old post...

Here a little sample of my code regarding how to use CodeContract via ContractAnnotation with Resharper:

    [ContractAnnotation("value:null=>true")]
    public static bool IsNullOrEmpty(this string value)
    {
        return string.IsNullOrEmpty(value);
    }

It is very simple...if u find the breadcrumb in the wood. You can check other cases too.

Have a nice day

我做我的改变 2024-10-13 21:46:45

Q1:因为Resharper不做路径分析。它只是看到可能的 null 引用并对其进行标记。

Q2:如果不执行您已经提供的任何一项操作,您就无法做到这一点。

Q1: Because Resharper doesn't do path analysing. It just sees a possible null reference and flags that.

Q2: You can't without doing either of what you provided already.

够钟 2024-10-13 21:46:45

您确实知道(或期望)如果存在空引用,此代码将引发异常:

ComponentException<MyUserManagerException>.FailIfTrue([...]);

但是,由于没有指定此内容的契约,ReSharper 必须假设这只是一个正常的方法调用,可能会返回而不引发任何异常无论如何。

使此方法实现 ReSharper 合约,或作为一个简单的解决方法(仅影响调试模式,因此发布模式不会造成性能损失),就在 FailIfTrue 调用之后:

Debug.Assert(user != null);

这将消除警告,作为额外的好处,在调试模式下进行运行时检查,以确保确实满足您在调用 FailIfTrue 后假设的条件。

You do know (or expect) that this code will throw an exception if there is a null reference:

ComponentException<MyUserManagerException>.FailIfTrue([...]);

However, since there is no contract specifying this, ReSharper has to assume that this is just a normal method call which may return without throwing any exception in any case.

Make this method implement the ReSharper contract, or as a simple workaround (which only affects debug mode, therefore no performance penalty for release mode), just after the FailIfTrue call:

Debug.Assert(user != null);

That will get rid of the warning, and as an added bonus do a runtime check in debug mode to ensure that the condition assumed by you after calling FailIfTrue is indeed met.

尛丟丟 2024-10-13 21:46:45

这是由 Resharper 引擎引起的。这些“可能的 NullReferenceException”的发生是因为有人(可能在 Resharper)在该方法的某处声明/配置了注释。

它的工作原理如下: ReSharper NullReferenceException 分析和它的契约

不幸的是,有时这些有用的注释是错误的。

当您检测到错误时,应将其报告给 JetBrains,他们将在下一个版本中更新注释。他们已经习惯了这个。

同时,您可以尝试自行修复。阅读文章了解更多:)

This is caused by the Resharper engine. These "possible NullReferenceException" happen because someone (probably at Resharper) has declared/configured somewhere an annotation on the method.

Here is how it works: ReSharper NullReferenceException Analysis and Its Contracts

Unfortunately, sometimes, these useful annotation are just wrong.

When you detect an error, you should report it to JetBrains and they will update the annotations on the next release. They're used to this.

Meanwhile, you can try to fix it by yourself. Read the article for more :)

居里长安 2024-10-13 21:46:45

如果检查给定代码上方,请检查您是否有任何 user==null。如果存在,则 ReSharper 认为该变量“可以为 null”,因此建议您在引用它之前使用检查/断言。在某些情况下,这是 ReSharper 猜测变量是否可以为 null 的唯一方法。

Please check if you have any user==null if check above the given code. If there is, then ReSharper thinks that the variable "can be null" so recommends you to use a check/assert before referencing it. In some cases, that's the only way ReSharper can guess whether a variable can or cannot be null.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文