我有以下方法:
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# 规范的那一部分),如果他们想要允许推断一半的类型而另一半不推断(特别是考虑到你可以仅通过泛型参数的数量来重载方法这一事实)将会显着增加。
关于c# - 如何让 C# 编译器推断泛型类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1208764/