如何使C#编译器推断通用类型? [英] How to get the C# compiler to infer generic types?

查看:57
本文介绍了如何使C#编译器推断通用类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法:

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

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

Right now, a user of this method has to use it like this:

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

为什么必须在方法定义中指定TResult?自从我在TGenericType中指定TResult以来,编译器就已经知道TResult。理想情况下(如果C#编译器更聪明),我的方法将如下所示:

Why do I have to specify TResult in the method defintion? The compiler already knows TResult since I specified it in TGenericType. Ideally (if the C# compiler was a little smarter), my method would look like this:

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

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

So the user could just simply use it like this:

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

是否可以做我想做的事情?

Is there a way to do what I want to do?

推荐答案

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

The C# specification does not allow inferring half of type arguments. You should either let the compiler to infer all the type arguments (which is not always applicable, like in your case) or manually specify all of them.

UPDATE (回复评论):虽然我不在C#团队中不能对您的问题给出绝对的答案,但我的猜测是过载解析的复杂性(这已经令人难以置信;您知道,如果您请阅读C#规范的那一部分),如果他们想允许一半类型的推断,而另一半则不允许(特别是考虑到您可以仅通过泛型参数的数量重载方法的事实),则将显着增加。

UPDATE (reply to comment): While I'm not on the C# team to give an absolute answer to your question, my speculation is that the complexity of overload resolution (which is already mind-blowing; you know that if you read that section of C# specification) would increase significantly if they wanted to allow half of types to be inferred and half not (especially considering the fact that you can overload methods solely by the number of generic arguments).

这篇关于如何使C#编译器推断通用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆