假设有以下类...
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());
FooBase<TBar>
,我们在这里说,在你知道TBar
是什么类型之后,FooBase<TBar>
将变成FeeBase<ActualType>
。由于我们在推断完成之前不知道类型,因此无法将此约束用作类型推断的一部分。这将是循环逻辑。 - AaronLS