匿名类
1. 第一步:定义一个类,类中有三个属性Id。Name.Height 属性类型根据“=”右边的值来推断
2. 第二步:创建这个类的对象,然后,用变量p1去指向它
3. var 表示根据右边的类型去推断var的类型
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace 匿名类 { class Program { static void Main(string[] args) { var p1 = new{ Id=1,Name="rupeng",Height=179}; Console.WriteLine(p1.Id+"====="+p1.Name); Console.ReadKey(); } } }
在Reflector中查看匿名类的C#代码
- 匿名类中的属性不能赋值:p1.Name="xcl";(不可以)反编译查看知道,这些匿名类中的属性只能是只读的。