为什么不能嵌套泛型类型推断? [英] Why can't nested generic types be inferred?

查看:242
本文介绍了为什么不能嵌套泛型类型推断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于以下类...

 公共抽象类FooBase< TBAR>其中,TBAR:BarBase {}
公共抽象类BarBase {}
公共类BAR1:BarBase {}
公共类Foo1:FooBase< BAR1> {}
 

...和下​​面的方法...

 公共TBAR DoSomething的< TFoo,TBAR>(TFoo theFoo),其中TFoo:FooBase< TBAR>其中,TBAR:BarBase
{
    返回默认(TBAR);
}
 

为什么不能对code以下行暗示的返回类型?

  BAR1 myBar = DoSomething的(新Foo1());
 

相反,我必须指定这样的泛型类型...

  BAR1 myBar = DoSomething的< Foo1,BAR1>(新Foo1());
 

解决方案

方法类型推断忽略的方法类型参数(*)泛型约束。这可以通过比较的参数的作出的形参类型的方法类型推断的原因只有扣除的。由于出现在您的形式参数类型的唯一泛型类型参数是TFoo,有没有办法来演绎TBAR。

很多人认为这样的设计决策是错误的,错,错。虽然我拿他们的观点,这个决定不会导致什么都在我看来,一些不错的性能。有关此问题的一个扩展的辩论,看到这个博客文章bazillion左右的意见告诉我,我错了,错了,错的:

<一个href="http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx">http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx


(*)请注意,我说的对的的方法类型参数的被忽略,不是一般的约束限制。如果推导出正式的参数类型构造泛型类型,确保施工违反的及其的类型参数约束那么这实际上将导致类型推断失败,该方法不适合重载的候选人。但在任何情况下,我们做的使来自比嗯,这显然是行不通的其他约束的扣除的。

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());

解决方案

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".

这篇关于为什么不能嵌套泛型类型推断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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