Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 views
in Technique[技术] by (71.8m points)

c# - Why can't nested generic types be inferred?

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());
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...