C#3.0的新特性

來源:互聯網
上載者:User
/* *============================主要示範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);        }    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.