问题描述
public static T Foo<T> (this ISomething smth,string param) where T : struct { ... }
public static T? Foo<T> (this ISomething smth,string param) where T : struct { ... }
var result = mySmth.Foo<bool>("Param");
我希望 result
是 bool
类型,但编译器说它是 bool?
类型 - 为什么会这样?如何强制编译器调用正确的重载?
解决方法
不能让重载(包括扩展)仅因返回类型而异。最好的选择是使用 Nullable
public static T Foo<T> (this ISomething smth,string param) where T : struct { ... }
public static T? NullableFoo<T> (this ISomething smth,string param) where T : struct { ... }