object
和var
之间有什么区别?
var
- Not specifying the type explicitly. Letting compiler figure out what that type is.
Pauli
noted in a comment, you get intelliSense
. var i;
won't compile. Anonymous Types
. You get intelliSense
. object
- System.Object
. intelliSense
. var i = 0; // i is of type `System.Int32`. Same as "int i = 0;"
i = "Some String"; // Compile time error.
object o = 0;
o = "Some String"; // Works
for example:
var i = 2;
object j = 2;
and you look at it in ildasm:
IL_0000: nop
IL_0001: ldc.i4.2
IL_0002: stloc.0
IL_0003: ldc.i4.2
IL_0004: box [mscorlib]System.Int32
IL_0009: stloc.1
You can see object item should be boxed and var item no need to boxing.
Also you can do:
object i; i = 2;
but you can't do:
var i; i = 2;
you will get compile error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.