Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/274.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ReSharper是如何知道的;表达永远是真实的;?_C#_Resharper - Fatal编程技术网

C# ReSharper是如何知道的;表达永远是真实的;?

C# ReSharper是如何知道的;表达永远是真实的;?,c#,resharper,C#,Resharper,请查看以下代码: private void Foo(object bar) { Type type = bar.GetType(); if (type != null) // Expression is always true { } } ReSharper声称type永远不会为null。这对我来说是显而易见的,因为总是会有一种类型的bar,但是ReSharper是怎么知道的呢?它怎么知道一个方法的结果永远不会是空的 类型不是结构,所以不能是结构。如果该方

请查看以下代码:

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

    if (type != null) // Expression is always true
    {   
    }
}
ReSharper声称
type
永远不会为
null
。这对我来说是显而易见的,因为总是会有一种类型的
bar
,但是ReSharper是怎么知道的呢?它怎么知道一个方法的结果永远不会是空的

类型
不是结构,所以不能是结构。如果该方法是由我编写的,那么返回值肯定是
null
(不一定是GetType,而是其他内容)


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

GetType
不是
虚拟的。你在上一次陈述中的假设很可能是正确的


编辑:回答您的评论问题-它无法使用现成的方法进行推断。

对象。GetType
不是虚拟的,因此您不能自己实现返回空值的版本。因此,如果
bar
为空,您将得到
NullReferenceException
,否则,
type
将永远不会为空。

是的,它基本上了解一些众所周知的方法。对于字符串连接,您也应该找到相同的方法,例如:

string x = null;
string y = null;
string z = x + y;

if (z == null)
{
    // ReSharper should warn about this never executing
}

现在,同样的信息也可以通过代码契约获得——我不知道JetBrains是直接连接到这些信息,有自己的数据库,还是两者的混合体。

JetBrains完美地解释了ReSharper是如何在他们的数据库中做到这一点的

链接摘要(这个问题是关于
NotNullAttribute
):

我们分析了大部分.NET Framework类库以及NUnit Framework,并使用JetBrains.Annotations命名空间中的一组自定义属性,通过外部XML文件对其进行了注释,具体如下:


对不起,我的问题没有解释清楚。我的意思是,如果我实现了其他方法,那么与GetType()无关,Resharper无法推断结果永远不会为null。@RichK,你是对的。Resharper无法推断。对不起,我的问题没有解释清楚。我想说的是,如果我实现了其他方法,与GetType()无关,Resharper无法推断结果永远不会为空,因为有人提到了代码契约。@Sapph:真遗憾。也许它真的不知道字符串连接:(@JonSkeet,至少从ReSharper版本2018.2.3开始,它确实在您的确切代码片段中给出了此警告。如果您在回答中也提供了原因的简要摘要,这将很有帮助。
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)