互联网解决方案咨询

梦想有多大路就会有多远:作一颗IT量子
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C# 3.0新特性>匿名类型

Posted on 2008-02-23 18:04  互联网粒子  阅读(116)  评论(0编辑  收藏  举报
在初始化的时候根据初始化列表自动产生类型的一种机制。

典型的代码:
1class Program
2    {
3        static void Main(string[] args)
4        {
5            var x = new { a = 3, b = 5, c = "some text" };
6            Console.WriteLine(x.a.ToString());
7        }

8    }
很奇怪吧~~~
不要认为这个var x真的是没有类型,其实这又是一个编译器的魔术,
当我们编译这段代码的时候,编译器会自动产生以下类型定义:
 1class __Anonymous1
 2{
 3    private int _a = 3;
 4    private int _b = 5;
 5    private string _c = “some text”;
 6
 7    public int a get return _a; } set { _a = value; } }
 8    public int b get return _b; } set { _b = value; } }
 9    public int c get return _c; } set { _c = value; } }
10}