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

前端之家收集整理的这篇文章主要介绍了如何让C#编译器推断泛型类型?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下方法
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#规范)会显着增加.

原文链接:https://www.f2er.com/csharp/243143.html

猜你在找的C#相关文章