why var cannot be applied to member variable [duplicate]
Possible Duplicates:
Why class fields cannot be var? Implicit typing; why just local variables? var in C# - Why开发者_JS百科 can't it be used as a member variable?
the var type cannot be applied to the member variables. I want to know why?
Eric Lippert has a detailed blog post about this: Why no var on fields?
Summary:
- Even if it were feasible, it would require major compiler upheaval
- Determining the type could be very complex in some cases, and end up with some weird situations - what would be exposed for a public variable using an anonymous type?
I'd love it for simple cases, but the balance of "simple" may well be hard to decide in an elegant way which "feels right".
var can only be used in a local scope. The actual type must be inferred by the compiler and it is too hard/impossible to determine the type from a construct like this:
class Person
{
public var Name {get; set;}
}
To put it simply :
// code fragment
int Add(int x, int y) { return x + y; }
var x = Add(int x, int y); // the compiler will know that the result of the call will be of type int
class X
{
var x; // illegal, the compiler has no idea what's the target type of X
}
Because it's type is not known. This is related to build order of compiler.
You can also have a look at this topic.
精彩评论