为什么不能推断嵌套泛型类型?
给定以下类...
public abstract class FooBase<TBar> where TBar : BarBase{}
public abstract class BarBase{}
public class Bar1 : BarBase{}
public class Foo1 : FooBase<Bar1> {}
...以及以下方法...
public TBar DoSomething<TFoo, TBar>(TFoo theFoo)
where TFoo : FooBase<TBar>
where TBar : BarBase
{
return default(TBar);
}
为什么下面的代码行不能暗示返回类型?
Bar1 myBar = DoSomething(new Foo1());
相反,我必须指定像这样的通用类型......
Bar1 myBar = DoSomething<Foo1, Bar1>(new Foo1());
Given the following classes...
public abstract class FooBase<TBar> where TBar : BarBase{}
public abstract class BarBase{}
public class Bar1 : BarBase{}
public class Foo1 : FooBase<Bar1> {}
...and the following method...
public TBar DoSomething<TFoo, TBar>(TFoo theFoo)
where TFoo : FooBase<TBar>
where TBar : BarBase
{
return default(TBar);
}
Why can't the following line of code imply the return type?
Bar1 myBar = DoSomething(new Foo1());
Instead I have to specify the generic types like this...
Bar1 myBar = DoSomething<Foo1, Bar1>(new Foo1());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
方法类型推断忽略方法类型参数 (*) 的通用约束。方法类型推断仅推理通过将参数与形式参数类型进行比较可以进行的推论。由于形式参数类型中出现的唯一通用类型参数是 TFoo,因此无法推导 TBar。
许多人认为这个设计决策是错误的、错误的、错误的。尽管我同意他们的观点,但这个决定确实带来了我认为一些不错的特性。有关此问题的详细辩论,请参阅这篇博客文章中的大量评论,告诉我我错了,错了,错了:
http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx
(*) 请注意,我上述对方法类型参数的约束将被忽略,而不是一般的约束。如果推导的形式参数类型是构造泛型类型,使得该构造违反了其类型参数约束,则此事实会导致类型推断失败,并且该方法不是重载决议的候选者。但在任何情况下,除了“嗯,显然这行不通”之外,我们都不会从约束中进行推论。
Method type inference ignores generic constraints on the method type parameters (*). Method type inference reasons only about deductions that can be made by comparing arguments to formal parameter types. Since the only generic type parameter that appears in your formal parameter types is TFoo, there is no way to deduce TBar.
Many people believe this design decision to be wrong, wrong, wrong. Though I take their point, this decision does lead to what are in my opinion some nice properties. For an extended debate on this issue, see the bazillion or so comments on this blog article telling me that I am wrong, wrong, wrong:
http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx
(*) Note that I said constraints on method type parameters are ignored, not constraints in general. If the deduced formal parameter types are constructed generic types such that the construction violates their type parameter constraints then this fact causes type inference to fail and the method is not a candidate for overload resolution. But under no circumstances do we make a deduction from a constraint other than "Hmm, clearly this is not going to work".