C# ---扩展方法
????? 雖然自己以前用過擴展方法,但是從來沒有認真總結過什么是擴展方法,前天面試被問到什么是擴展方法,在什么情況下使用,沒答出來,現在在網上找了一下,做個小結,希望能看到此文的朋友給出指正。
????? 在項目中經常要引用到別人的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();
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
轉載于:https://www.cnblogs.com/liuxvpiaopiao/archive/2011/07/13/2105386.html
總結
以上是生活随笔為你收集整理的C# ---扩展方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TIOBE 2011年7月编程语言排行榜
- 下一篇: [转载] C#面向对象设计模式纵横谈——