VaR Employee = new {age = 25, name = "James "}
You do not need to declare a class, and you can get the context variable -- closure in the initialization tool.
This is the anonymous type provided in C #3.0.
In addition, the declared type can be accessed as follows:
String name = employee. Name;
Let's take a look at the implementation of Il.
. Method public hidebysig instance void dd () cel managed
{
// Code Size 22 (0x16)
. Maxstack 3
. Locals Init ([0] class' <> F _ anonymoustype0 '2' <int32, string> employee,
[1] string name)
Il_0000: NOP
Il_0001: LDC. i4.s 25
Il_0003: ldstr "James"
Il_0008: newobj instance void class '<> F _ anonymoustype0 '2' <int32, string >::. ctor (! 0,
! 1)
Il_000d: stloc.0
Il_000e: ldloc.0
Il_000f: callvirt instance! 1 class '<> F _ anonymoustype0 '2' <int32, string >:: get_name ()
Il_0014: stloc.1
Il_0015: Ret
} // End of method testvar: dd
When you see the code, you will think, '<> F _ anonymoustype0 '2', where does it come from?
Let's see the Il view.
Although the anonymous type is very convenient, we cannot use the code to access '<> F _ anonymoustype0 '2', and VAR cannot define global variables and parameter types, therefore, the created anonymous instance can only be applied within the function. This restricts the use of the anonymous type.