C# —擴充方法

來源:互聯網
上載者:User

      雖然自己以前用過擴充方法,但是從來沒有認真總結過什麼是擴充方法,前天面試被問到什麼是擴充方法,在什麼情況下使用,沒答出來,現在在網上找了一下,做個小結,希望能看到此文的朋友給出指正。

      在項目中經常要引用到別人的dll,假設dll中有個student類, 該類中只有GetName()方法,如果需要GetAge()方法,有不能修改Dll源碼,該怎麼辦呢?此時有兩個辦法,一是繼承student類,二是擴充student中的方法,這裡我們來介紹擴充方法,首先來建一個cs檔案,實現student類:

 

  public class student

{

  public student(){}

  public string name { get; set; }

  public int age {set;get;}

  public student(string name,int age)

  {

     this.age = age;

     this.name = name;

  }

}

編譯後這個檔案將形成Dll,我們在Aspx的後台頁面實現一下代碼:

static class exStudent //這裡必須是靜態類

{

 public static int GetAge(this student st) {return st.age};

 }

這樣就成功擴充了student類的方法;可如下使用GetAge()方法

student st = new student("AA",12);

st.GetAge();

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

聯繫我們

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