【发布时间】:2021-01-05 09:45:03
【问题描述】:
我有以下两种方法:
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? - 为什么会这样?如何强制编译器调用正确的重载?
【问题讨论】:
-
我也尝试将第二个更改为
public static T? Foo<T?> (...),但没有任何改变。 -
您确定重载方法可以仅根据返回类型而有所不同吗?
-
也许不是,编译器只允许这样做,因为它们都是扩展方法。是否有一个好的解决方法可以使其适用于可空和不可空值类型?
-
你不能在同一个
static class中同时拥有这两个定义。 -
“我有以下两种方法”——不,你没有:dotnetfiddle.net/AqNDdQ