• λ我爱Aspx >> C#.Net >> C# 3.0新特性初步研究 Part5:匿名类型_C#教程
  • C# 3.0新特性初步研究 Part5:匿名类型_C#教程

  • :aspxer  Դ:internet  :2007-4-28 20:57:56  ؼ:c#
  • 匿名类型(Anonymouse Type)——这年头什么多系都匿名了 : )

    在初始化的时候根据初始化列表自动产生类型的一种机制。

    典型的代码:

    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}

    11

    这样就不会和我前面所的var必须初始化,并且必须让编译器“猜得出”正确的类型这一句话产生矛盾。

    PS:再过20年估计编译器就什么都可以做了,还是行业专家,“老板,买一个针对电信行业的编译器,要带SP增值服务扩张包的”

    http://zc1984.cnblogs.com/archive/2006/06/10/422715.html

    Ҷƪл˵?
  • һƪC# 3.0新特性初步研究 Part4:使用集合类型初始化器_C#教程
    һƪC# 3.0新特性初步研究 Part6:使用查询表达式 _C#教程