C#3.0的新特性

/*
 *============================主要演示C#3.0的新特性=====================
 *一、自动属性
 *二、对像和集合初始化器
 *三、扩展方法
 *四、Lambda表达式
 * 13/6/2010 Berlin
 * 
 */
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinqTest
{

    //演示自动属性
    public class Point
    {
        public int X { get; set; }//自动化属性

        public int Y { get; private set; }//带修饰符的自动化属性

        public int T { get; set; }
    }


    //演示对像和集合初始化器;
    class Test_45
    {
        Point p = new Point { X = 23, T =2};//可以通这种方式来实例化一个对像

        //初始化一个集合
        List<Point> PoList = new List<Point> 
                                     {
                                        new Point {X =2,T =3},
                                        new Point {X =4,T=2},
                                        new Point {X=23,T =90}
                                     };
        
    }


    //演示扩展方法,所谓扩展方法是指在C#3.0中,对于已经编译的程序集,在不需要重新编译源有代码或不公开源代码的程序集中添加相关方法
    //点评,对于调用 第三方API,在没有源代码的情况下想扩展相关功能,就用它啦
    //实现:用一个静态类,静态方法的第一个参数中传入要扩展的类名形如:this class object

    static class ExtensionsFunction
    {
        //对Point 扩展了一个方法GetZeroPoint
        public static  Point GetZeroPoint(this Point p)
        {
            return new Point { X = 0, T = 0 };
        }

        //对类Test_45扩展了一个显示自已类全名的方法
        public static void ShowSelfInfo(this Test_45 obj)
        {
            Console.WriteLine(obj.GetType().Assembly.FullName);
        }
    }


    //使用扩展方法
    public class TestExtension
    {
        public void TestExtenSionFuntion()
        {
            Point p = new Point { X = 8,T = 9 };
            Test_45 t = new Test_45();

            p.GetZeroPoint();//调用了Point的一个扩展方法,注意这个方法在类Point中是没有的

            t.ShowSelfInfo();
           
        }
        
    }

    //演示Lambda表达式
    //Lambda表达式是一种简化的匿名方法
    //有如下几种表现形式
    // (int x)=>{return x+1;}
    //(int x)=>x+1;
    //x=>x+1;
    //(x,y)=>x+y;
    public class LambdaTest
    {
        public void TestLambda()
        {
            List<Point> pList = new List<Point> 
                                        {
                                            new Point {X =2,T =3},
                                            new Point {X =4,T=1}
                                        };

            List<Point> ppList = new List<Point>();
            ppList = pList.FindAll(p => p.X > 2 && p.T < 3);
        }


    }
}

posted @ 2010-06-17 20:56  风清云淡  阅读(335)  评论(0编辑  收藏  举报