C#2.0 C#3.0 語言特性

來源:互聯網
上載者:User

C#2.0 語言特性

範型Generics
使類或方法獲得型別參數變得功能強大。 

委託Delegates
可以封裝一個或多個方法的類,可以理解為方法的介面
delegate void SimpleDelegate();
delegate int ReturnValueDelegate();
delegate void TwoParamsDelegate( string name, int age );
//Delegate instantiation (C# 1.x)
public class DemoDelegate
{
    void MethodA() { … }
    int MethodB() { … }
    void MethodC( string x, int y ) { … }

    void CreateInstance()
        {
             SimpleDelegate a = new SimpleDelegate( MethodA );
             ReturnValueDelegate b = new ReturnValueDelegate ( MethodB );
             TwoParamsDelegate c = new TwoParamsDelegate( MethodC );
         }
}
//Delegate instantiation (C# 2.0)
public class DemoDelegate
{
    void MethodA() { … }
    int MethodB() { … }
    void MethodC( string x, int y ) { … }

    void CreateInstance()
   {
        SimpleDelegate a = MethodA;
        ReturnValueDelegate b = MethodB;
        TwoParamsDelegate c = MethodC;
    }
}
匿名方法Anonymous Methods
允許我們定義委派物件可以接受的代碼塊。這個功能省去我們建立委託時想要傳遞給一個委託的小型代碼塊的一個額外的步驟
delegate void SimpleDelegate();
public class DemoDelegate
{
    void Repeat10Times( SimpleDelegate someWork )
    {
        for (int i = 0; i < 10; i++) someWork();
    }

    void Run2() {
        int counter = 0;
        this.Repeat10Times( delegate {
            Console.WriteLine( "C# chapter" );
            counter++;
        } );
        Console.WriteLine( counter );
    }
}
不使用匿名方法則需要
public class Writer {
    public string Text;
    public int Counter;
    public void Dump() {
        Console.WriteLine( Text );
        Counter++;
    }
}
public class DemoDelegate
{
    void Repeat10Times( SimpleDelegate someWork )
    {
        for (int i = 0; i < 10; i++) someWork();
    }
    void Run1()
    {
         // Writer 類中實現了SimpleDelegate 委託的方法
        Writer writer = new Writer();
        writer.Text = "C# chapter";
        this.Repeat10Times( writer.Dump );
        Console.WriteLine( writer.Counter );
    }  
}

迭代器和Enumerators and Yield
迭代器是一種方法、get訪問器或運算子,使得開發人員能在類或結構中支援foreach迭代,而不必實現實現整個 IEnumerator介面

迭代器特點:
迭代器是可以返回相同類型的值的有序序列的一段代碼。
迭代器可用作方法、運算子或 get 訪問器的代碼體。
迭代器代碼使用 yield return 語句依次返回每個元素。yield break 將終止迭代。
可以在類中實現多個迭代器。每個迭代器都必須像任何類成員一樣有唯一的名稱,並且可以在 foreach 語句中被用戶端代碼調用
迭代器的傳回型別必須為
IEnumeable ,IEnumerator,IEnumeable <T>,IEnumerator<T>
 
實現代碼:
class StudentList
{
        string student1 = "甲";
        string student2 = "乙";
        string student3 = "丙";
        string student4 = "丁";
        string student5 = "戊";
        public string Student1
        {
                get{return student1;}
                set{student1 = value;}
        }
 
        public string Student2
        {
                get{ return student2;}
                set{student2 = value;}
        }
 
        public string Student3
        {
                get{return student3;}
                set{student3 = value;}
        }
 
        public string Student4
        {
                get{ return student4; }
                set{ student4 = value;}
        }
 
        public string Student5
        {
          get   {  return student5;  }
          set   {  student5 = value; }
       }

       //編寫該類的迭代器(實現System.Collections.IEnumerator 介面)
      public System.Collections.IEnumerator GetEnumerator()
      {
                //通過for迴圈對StudentList類中的5個string類型變數進行處理
                for(int i=0;i<5;i++)
                {
                    switch (i)
                    {
                        case 0:
                            yield return student1;
                            break;
                        case 1:
                            yield return student2;
                            break;
                        case 2:
                            yield return student3;
                            break;
                        case 3:
                            yield return student4;
                            break;
                        case 4:
                            yield return student5;
                            break;
                    }
                }
        }
}
 
在main函數中:
//通過foreach使用迭代器獲得StudentList對象中的欄位值
StudentList myStudentList = new StudentList();
foreach (object student in myStudentList)
{
 Console.WriteLine(student.ToString());
}

C#3.0語言特性

局部類型推導Local Type Inference
定義可變類型變數
var x = 2.3;             // double
var s = "sample";        // string

Lambda運算式
allow the definition of anonymous methods using more concise syntax.
所有的Lambda式都使用操作符“=>“,表示“goes to (轉變為)”。
操作符左邊部分是輸入參數表,右邊部分是運算式或語句塊。x => x * x 讀成“x轉變為x 乘x”。
delegate int del(int i);
del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25

擴充方法Extension Methods
C#是一種物件導向的程式設計語言,允許通過繼承擴充類。但是,設計一個類可以安全的繼承並且將來可以很好的維護是很難的。除非類被設計為可被繼承的,可以通過申明類為sealed。但是這樣安全性就與靈活性衝突。
C# 3.0 introduces a syntax that conceptually extends an existing type (either reference or value) by adding new methods without deriving it into a new type.
//傳統方法
static class Traditional
{
    public static void Demo()
   {
        decimal x = 1234.568M;
        Console.WriteLine( FormattedUS( x ) );
        Console.WriteLine( FormattedIT( x ) );
    }
    public static string FormattedUS( decimal d )
    {
        return String.Format( formatIT, "{0:#,0.00}", d );
    }
    public static string FormattedIT( decimal d )
    {
        return String.Format( formatUS, "{0:#,0.00}", d );
    }
    static CultureInfo formatUS = new CultureInfo( "en-US" );
    static CultureInfo formatIT = new CultureInfo( "it-IT" );
}
//擴充方法
static class ExtensionMethods
{
    public static void Demo()
    {
        decimal x = 1234.568M;
        Console.WriteLine( x.FormattedUS() );
        Console.WriteLine( x.FormattedIT() );
        Console.WriteLine( FormattedUS( x ) ); // Traditional call allowed
        Console.WriteLine( FormattedIT( x ) ); // Traditional call allowed
    }
    static CultureInfo formatUS = new CultureInfo( "en-US" );
    static CultureInfo formatIT = new CultureInfo( "it-IT" );
    public static string FormattedUS( this decimal d )
    {
        return String.Format( formatIT, "{0:#,0.00}", d );
    }

    public static string FormattedIT( this decimal d )
    {
        return String.Format( formatUS, "{0:#,0.00}", d );
    }
}

對象初始設定式Object Initialization Expressions
C# 3.0 introduces a shorter form of object initialization syntax that generates functionally equivalent code。
C# 3.0 使用更短的對象初始化文法,這種文法同樣可以實現對象的初始化。
//傳統方法
Customer customer = new Customer();
customer.Name = "Marco";
customer.Country = "Italy";
//使用Object Initialization Expressions
Customer customer = new Customer { Name = "Marco", Country = "Italy" };

匿名型別Anonymous Types
An object initializer can also be used without specifying the class that will be created with the new operator. Doing that, a new class-an anonymous type-is created.
可以使用new操作符在不宣告類型的情況下即可初始一個對象。這就是匿名方法。
Customer c1 = new Customer { Name = "Marco" };
var c2 = new Customer { Name = "Paolo" };
var c3 = new { Name = "Tom", Age = 31 };
var c4 = new { c2.Name, c2.Age };
var c5 = new { c1.Name, c1.Country };
var c6 = new { c1.Country, c1.Name };
變數c1,c2是Customer類型,c4,c5,c6沒有宣告類型。但是可以從代碼的上下文中推出c4,c5,c6為Customer類型。

查詢運算式Query Expressions
C# 3.0 also introduces query expression_rs, which have a syntax similar to the SQL language and are used to manipulate data. This syntax is converted into regular C# 3.0 syntax that makes use of specific classes, methods, and interfaces that are part of the LINQ libraries. We would not cover all the keywords in detail because it is beyond the scope of this chapter. We will cover the syntax of query expression_rs in more detail in Chapter 4, “LINQ Syntax Fundamentals.”
In this section, we want to introduce the transformation that the compiler applies to a query expression_r, just to describe how the code is interpreted.
Here is a typical LINQ query:
// Declaration and initialization of an array of anonymous types
var customers = new []{
    new {  Name = "Marco", Discount = 4.5 },
    new {  Name = "Paolo", Discount = 3.0 },
    new {  Name = "Tom", Discount = 3.5 }
};
 var query =
    from c in customers
    where c.Discount > 3
    orderby c.Discount
    select new { c.Name, Perc = c.Discount / 100 };
foreach( var x in query ) {
    Console.WriteLine( x );
}
A query expression_r begins with a from clause (in C#, all query expression_r keywords are case sensitive) and ends with either a select or group clause. The from clause specifies the object on which LINQ operations are applied, which must be an instance of a class that implements the IEnumerable<T> interface.
That code produces the following results:
{ Name = Tom, Perc = 0.035 }
{ Name = Marco, Perc = 0.045 }
C# 3.0 interprets the query assignment as if it was written in this way:
var query = customers
            .Where( c => c.Discount > 3)
            .OrderBy( c => c.Discount )
            .Select( c=> new { c.Name, Perc = c.Discount / 100 } );

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.