Possibility of external functions as nullable guards?

前端 未结 2 1363
囚心锁ツ
囚心锁ツ 2020-12-06 13:39

C# 8 introduced nullable reference types, which is a very cool feature. Now if you expect to get nullable values you have to write so-called guards:



        
2条回答
  •  时光取名叫无心
    2020-12-06 14:25

    There are a few things you can do.

    You can use [DoesNotReturnIf(...)] in your guard method, to indicate that it throws if a particular condition is true or false, for example:

    public static class Ensure
    {
        public static void True([DoesNotReturnIf(false)] bool condition)
        {
            if (!condition)
            {
                 throw new Exception("!!!");   
            }
        }
    }
    

    Then:

    public void TestMethod(object? o)
    {
        Ensure.True(o != null);
        Console.WriteLine(o.ToString()); // No warning
    }
    

    This works because:

    [DoesNotReturnIf(bool)]: Placed on a bool parameter. Code after the call is unreachable if the parameter has the specified bool value


    Alternatively, you can declare a guard method like this:

    public static class Ensure
    {
        public static void NotNull([NotNull] object? o)
        {
            if (o is null)   
            {
                throw new Exception("!!!");
            }
        }
    }
    

    And use it like this:

    public void TestMethod(object? o)
    {
        Ensure.NotNull(o);
        Console.WriteLine(o.ToString()); // No warning
    }
    

    This works because:

    [NotNull]: For outputs (ref/out parameters, return values), the output will not be null, even if the type allows it. For inputs (by-value/in parameters) the value passed is known not to be null when we return.

    SharpLab with examples


    Of course, the real question is why you want to do this. If you don't expect value to be null, then declare it as object?, rather than object -- that's the point of having NRTs.

提交回复
热议问题