问题
Does anyone know or care to speculate why implicit typing is limited to local variables?
var thingy = new Foo();
But why not...
var getFoo() {
return new Foo();
}
回答1:
Eric Lippert did an entire blog post on the subject.
- http://blogs.msdn.com/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx
In summary, the main problem is that it would have required a major re-architecture of the C# compiler to do so. Declarations are currently processed in a single pass manner. This would require multiple passes because of the ability to form cycles between inferred variables. VB.net has roughly the same problem.
回答2:
Jared has a fantastic link in his answer, to a fantastic topic.
I think it does not answer the question explicitly.
Why not?
var getFoo() {
return new Foo();
}
The reason for this is:
What if?
class Foo {}
var GetFoo() {
return GetBar();
}
var GetBar() {
return GetBaz();
}
var GetBaz() {
return new Foo();
}
You could deduce that GetFoo
is going to return Foo
, but you will have to trace through all the calls that method makes and its children makes just to infer the type. As it stands the C# compiler is not designed to work in this way. It needs method and field types early in the process before the code that infers types can run.
On a purely aesthetic level I find the var definitions on methods confuse things. Its one place where I think being explicit always helps, it protects you from shooting your self in the foot by accidentally returning a type that causes your signature and a ton of other dependent method signatures to change. Worst still, you could potentially change all you signatures of a method chain without even knowing you did so if you return the value of a method that returns object and happened to be lucky.
I think var methods are best left for dynamic languages like Ruby
回答3:
Because it is much easyer to do. If you were to inference all types, one would need something like Hindley Milner type inference system which will in make your beloved C# into Haskel derivative language.
回答4:
Essentially, the issue you are running into is that C# (thus far) is a statically typed language. A local variable defined as var is still statically typed, but syntactically hidden. A method returning var, on the other hand, has many implications. It becomes more of an interface for usage, and you don't gain anything by using var.
回答5:
you can use in vs 2010 Dynamic
Dynamic getFoo() {
return new Foo();
}
回答6:
I think it's because the scope of that implied type is much wider and therefore more likely to cause problems than within the scope of a single method.
来源:https://stackoverflow.com/questions/824739/implicit-typing-why-just-local-variables