微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。