gpt4 book ai didi

c# - ReSharper 如何知道 "Expression is always true"?

转载 作者:可可西里 更新时间:2023-11-01 08:19:24 27 4
gpt4 key购买 nike

检查以下代码:

private void Foo(object bar)
{
Type type = bar.GetType();

if (type != null) // Expression is always true
{
}
}

ReSharper 声称 type 永远不会是 null。这对我来说很明显,因为 bar 总是有一个类型,但 ReSharper 是如何知道的?它怎么知道方法的结果永远不会是 null

Type 不是结构,所以不可能是这样。而如果这个方法是我写的,那么返回值肯定可以是null(不一定是GetType,而是别的什么)。

ReSharper 是否足够聪明,知道只有那个特定方法的结果永远不会是 null? (就像有一个永远不会返回 null 的已知 .NET 方法的硬编码列表。)

最佳答案

JetBrains 在其 features list 中完美地解释了 ReSharper 如何做到这一点.

来自链接的摘要(这个特定问题是关于 NotNullAttribute):

We have analyzed a great share of .NET Framework Class Library, as well as NUnit Framework, and annotated it through external XML files, using a set of custom attributes from the JetBrains.Annotations namespace, specifically:

StringFormatMethodAttribute (for methods that take format strings as parameters)
InvokerParameterNameAttribute (for methods with string literal arguments that should match one of caller parameters)
AssertionMethodAttribute (for assertion methods)
AssertionConditionAttribute (for condition parameters of assertion methods)
TerminatesProgramAttribute (for methods that terminate control flow)
CanBeNullAttribute (for values that can be null)
NotNullAttribute (for values that can not be null)
UsedImplicitlyAttribute (for entities that should not be marked as unused)
MeansImplicitUseAttribute (for extending semantics of any other attribute to mean that the corresponding entity should not be marked as unused)

关于c# - ReSharper 如何知道 "Expression is always true"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5067819/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com