简体   繁体   English

JetBrains Rider中的自定义null断言

[英]Custom null assertion in JetBrains Rider

I have a custom extension method for checking Guid? 我有一个自定义扩展方法来检查Guid? values: 值:

public static bool IsNullOrDefault(this Guid? guid)
{
    return !guid.HasValue || guid.value == Guid.Empty;
}

When I use the method in my code, I would expect that Rider will consider this method in possible System.InvalidOperationException assertions. 当我在代码中使用该方法时,我希望Rider会在可能的System.InvalidOperationException断言中考虑此方法。 But it does not. 但事实并非如此。

public void Foo(Guid? guid)
{
    if (guid.IsNullOrDefault())
    {
        throw new Exception();
    }

    var x = guid.Value;
            ^ There is still a yellow squiggle here, saying Possible System.InvalidOperationException
    ...
}

I have tried creating my own Null Checking pattern by overwriting the Custom (statement) pattern: 我尝试通过覆盖自定义(语句)模式来创建自己的Null Checking模式:

if ($EXPR$.IsNullOrDefault()) throw new System.ArgumentNullException($NAME$);

But that does not work either. 但这也不起作用。 How can I configure Rider to consider my custom method an equivalent to guid.HasValue or guid != null ? 如何配置Rider以将我的自定义方法视为guid.HasValueguid != null

I'm not sure Rider is intelligent enough to recognize that you already checked this. 我不确定Rider是否足够聪明,无法识别出您已经检查了这一点。 I think what you can do instead, is use the ?. 我认为您可以改为使用?. notation to check for null 检查是否为null符号

var x = guid?.Value;

This check if guid is null before the .value is evaluated, and just return null if that's the case. 在评估.value之前,检查guid是否为null ,如果是这种情况,则仅返回null

Then you can put the check afterward instead, so it ends up like 然后,您可以将支票放到后面,这样它就会像

var x guid?.value;
if(x is null)
    Throw new Exception();

Or you can return a default value instead of throwing an exception, your call. 或者,您可以返回默认值,而不是引发异常(调用)。

Let me know how it works! 让我知道它是如何工作的!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM