【问题标题】:Generic overload for struct does not call correct method结构的泛型重载不调用正确的方法
【发布时间】: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&lt;T?&gt; (...),但没有任何改变。
  • 您确定重载方法可以仅根据返回类型而有所不同吗?
  • 也许不是,编译器只允许这样做,因为它们都是扩展方法。是否有一个好的解决方法可以使其适用于可空和不可空值类型?
  • 你不能在同一个static class中同时拥有这两个定义。
  • 我有以下两种方法”——不,你没有:dotnetfiddle.net/AqNDdQ

标签: c# c#-8.0


【解决方案1】:

您不能让重载(包括扩展)仅因返回类型而异。最好的选择是使用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

【讨论】:

  • 您能否详细说明Foo&lt;T&gt;Foo&lt;T?&gt; 之间的区别是如果两种方法都有where T : struct?编译器在第二种情况下会做不同的事情吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多