How to identify a nullable reference type for generic type?

后端 未结 2 1273
臣服心动
臣服心动 2021-01-13 13:41

In C# 8 with nullable enabled, is there a way to identify a nullable reference type for generic type?

For nullable value type, ther

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-13 14:35

    You can't use nullable in the constraint, but you can use it in the method signature. This effectively constraints it to be a nullable type. Example:

    static Result> Create(Nullable value) where T  : struct
    {
        //Do something
    }
    

    Note that you can use this side by side with your existing method, as an overload, which allows you to execute a different logic path if it's nullable versus if it is not.

    static Result> Create(Nullable value) where T  : struct
    {
        Log("It's nullable!");
        Foo(value);
    }
    
    public static Result Create(T value)
    {
        Log("It's not nullable!");
        Foo(value);
    }
    

提交回复
热议问题