Nullable reference types with generic return type

前端 未结 3 1415
忘掉有多难
忘掉有多难 2020-11-27 18:39

I\'m playing around a bit with the new C# 8 nullable reference types feature, and while refactoring my code I came upon this (simplified) method:

public T Get         


        
3条回答
  •  -上瘾入骨i
    2020-11-27 18:42

    In C# 9 you are able to express nullability of unconstrained generics more naturally:

    public T? Get(string key)
    {
        var wrapper = cacheService.Get(key);
        return wrapper.HasValue ? Deserialize(wrapper) : default;
    }
    

    Note there's no ! operator on the default expression. The only change from your original example is the addition of ? to the T return type.

提交回复
热议问题