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

6 c# compiler-construction

我有以下方法:

public TResult Get<TGenericType, TResult>()
                          where TGenericType : SomeGenericType<TResult>
                          where TResult : IConvertible {
   //...code that uses TGenericType...
   //...code that sets someValue...
   return (TResult) someValue;
}
Run Code Online (Sandbox Code Playgroud)

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

//Notice the duplicate int type specification
int number = Get<SomeGenericType<int>, int>();
Run Code Online (Sandbox Code Playgroud)

为什么我必须在方法定义中指定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;
}
Run Code Online (Sandbox Code Playgroud)

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

//Much cleaner
int number = Get<SomeGenericType<int>>();
Run Code Online (Sandbox Code Playgroud)

有办法做我想做的事吗?

Meh*_*ari 8

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

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