我正在使用新的C#8可空引用类型功能,并在重构我的代码时,我遇到了这个(简化)方法:
public T Get<T>(string key)
{
var wrapper = cacheService.Get(key);
return wrapper.HasValue ? Deserialize<T>(wrapper) : default;
}
Run Code Online (Sandbox Code Playgroud)
现在,这给出了一个Possible null reference return逻辑上的警告,因为default(T)将为所有引用类型赋予null.起初我以为我会把它改成以下内容:
public T? Get<T>(string key)
但这不可能做到.它说我要么必须添加通用约束where T : class或where T : struct.但是,这是不是一种选择,因为这既可以是(我可以存储int或int?或实例FooBar在缓存或其他).我还读到了一个假定的新泛型约束,where class?但似乎没有用.
我能想到的唯一简单的解决方案是使用null forgiving运算符更改return语句:
return wrapper.HasValue ? Deserialize<T>(wrapper) : default!;
Run Code Online (Sandbox Code Playgroud)
但这感觉不对,因为它肯定是空的,所以我基本上对这里的编译器撒谎:-)
我怎样才能解决这个问题?我错过了一些完全明显的东西吗?