struct 的通用重载不会调用正确的方法

问题描述

我有以下两种方法

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");

我希望 resultbool 类型,但编译器说它是 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 { ... }   

https://dotnetfiddle.net/PPZOhm