开发者

C# constructor generic parameters inference [duplicate]

This question already has answers here: Why doesn't C# support implied generic types on class constructors? 开发者_如何学Go (3 answers) Closed 9 years ago.

Why does C# infer generic parameters for methods but not for constructor?

new Tuple<int, int>(5, 5) vs. Tuple.Create(5, 5)


The other answers are wrong. There is no technical reason for this. The type could be inferred from the constructor call as it can from "normal" method calls.

Please refer to the answer by Eric Lippert (former C# compiler developer): Why can't the C# constructor infer type?


Consider the following:

public class Foo<T>
{
    public Foo(T value) { }
}

public class Foo
{
    public Foo(int value) { }
}

// suppose type parameter inference in constructor calls
var x = new Foo(5); // which one?

Because you can declare two types with the same name, one generic, and one non-generic, you need to unambiguously decide between them in the constructor call. Forcing the type parameters to be explicit is one way to remove any possible ambiguity. The language could have some resolution rules for this, but the benefits of this feature enough to spend the budget to implement it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜