加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何让C#编译器推断泛型类型?

发布时间:2020-12-15 08:19:06 所属栏目:百科 来源:网络整理
导读:我有以下方法: public TResult GetTGenericType,TResult() where TGenericType : SomeGenericTypeTResult where TResult : IConvertible { //...code that uses TGenericType... //...code that sets someValue... return (TResult) someValue;} 现在,这个
我有以下方法:
public TResult Get<TGenericType,TResult>()
                          where TGenericType : SomeGenericType<TResult>
                          where TResult : IConvertible {
   //...code that uses TGenericType...
   //...code that sets someValue...
   return (TResult) someValue;
}

现在,这个方法的用户必须像这样使用它:

//Notice the duplicate int type specification
int number = Get<SomeGenericType<int>,int>();

为什么我必须在方法定义中指定TResult?编译器已经知道了TResult,因为我在TGenericType中指定了它.理想情况下(如果C#编译器更聪明一点),我的方法看起来像这样:

public TResult Get<TGenericType>()
                          where TGenericType : SomeGenericType<TResult>
                          where TResult : IConvertible {
   //...code that uses TGenericType...
   //...code that sets someValue...
   return (TResult) someValue;
}

所以用户可以像这样简单地使用它:

//Much cleaner
int number = Get<SomeGenericType<int>>();

有办法做我想做的事吗?

解决方法

C#规范不允许推断一半的类型参数.您应该让编译器推断所有类型参数(这并不总是适用,如您的情况)或手动指定所有类型参数.

更新(回复评论):虽然我不是在C#团队中给出你的问题的绝对答案,但我的猜测是重载决策的复杂性(已经令人费解;你知道如果你阅读那个部分如果他们想要推断一半类型被推断而一半不被推断(特别是考虑到你可以仅通过泛型参数的数量来重载方法),那么C#规范)会显着增加.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读