[英]C# constraint generic parameter to a T<T2> for Fluent interface / compiler can't infer types
[英]How to get the C# compiler to infer generic types?
我有以下方法:
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#规范)会显着增加。
这取决于...
如果你只是使用SomeGenericType<TResult>
,你可以这样做:
public TResult Get<TResult>() where TResult : IConvertible {
SomeGenericType<TResult> myInstance = ...
//...code that sets someValue...
return (TResult) someValue;
}
在这种情况下,没有必要将第一种类型放在那里。 由于您的示例未明确地将SomeGenericType<TResult>
作为参数传递,因此它表明这是可能的。
否则,您需要完全指定所有通用参数。 不幸的是,这就是它在C#中的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.