泛型方法重载与可空类型不明确

Generic method overload ambiguous with nullable types

假设我有两个通用的重载方法,形式如下:

public string Do<T>(T maybeValue, Func<T, string> func)
  where T : class
{
  if(maybeValue == null) return null;
  return func(maybeValue);
}

public string Do<T>(T? maybeValue, Func<T, string> func)
  where T : struct
{
  if(!maybeValue.HasValue) return null;
  return func(maybeValue.Value);
}

现在,使用可空类型的变量调用方法,C# 拒绝编译并表示调用在两个重载之间不明确:

int? maybeX = 3;
Do(maybeX, x => x.ToString());

The call is ambiguous between the following methods or properties: 'Program.Do<int?>(int?, System.Func<int?,string>)' and 'Program.Do<int>(int?, System.Func<int,string>)'

简单的修复方法是在调用方法时包含通用参数,或指定 lambda 参数的类型:

Do<int>(maybeX, x => x.ToString());
Do(maybeX, (int x) => x.ToString());

有趣的是,在调用期间选择 int? 作为通用类型将无法编译

The type must be a reference type in order to use it as parameter 'T' in the generic type or method".

怎么会?显然,两个重载中只有一个可以与 int? 类型的值一起使用,但编译器说该调用不明确。我可以进一步限制方法以帮助编译器决定调用哪个方法,而无需调用代码明确指定类型吗?

where T : class 约束不是方法签名的一部分。该检查稍后在方法重载选择过程中进行。
这就是为什么它被认为是模棱两可的。在检查任何约束之前,这两种方法都是匹配的。
如果你明确地说 Do<int?> 只有第一个方法是匹配的,但是约束 'kicks in' 并确定它是无效的,因为 int? 不是引用类型。

如果您将其更改为:

,则会选择第二种方法
public static string Do<T>(T? maybeValue, Func<T?, string> func)
    where T : struct