前兩天看見擴展屬性,瞬間感覺微軟需要學習的東西實在是太多了,博大精深,我還差得很遠,以下的擴展方法就是一個很好的東西。
現在我先建立一個model

public class Student { public string Id { get; set; } public string Name { get; set; } }
在實際場景中,可能我們需要在這個model里需要寫一些方法,一些查詢等等,但是我們在設計時希望model里面只是聲明屬性,其它方法不放在model里面,那么怎么做到兩者兼容呢,擴展方法可以幫助到你,如下:
我們建立一個擴展類,
public static class StudentEx { public static int GetAge(this Student st) { return 1; } }
那么現在就可以直接調用了,調用如下:
Student st = new Student(); Console.WriteLine(st.GetAge());
是不是很簡單,我們可以任意在model外面為model加載擴展方法。