C#EnumExtensionsMethod
這篇介紹在C#上如果寫出Enum的Extensions方法。
enum & Extensions example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| namespace Test { public enum CityInTaiwan { Taipei = 0, NewTaipei = 1, Taoyuan = 2 } public static class Extensions { public static int getPersonsCount(this CityInTaiwan cityInTaiwan) { int personsCount = -1; switch (cityInTaiwan) { case CityInTaiwan.Taipei: personsCount = 1000000; return personsCount; case CityInTaiwan.NewTaipei: personsCount = 3000000; return personsCount; case CityInTaiwan.Taoyuan: personsCount = 2000000; return personsCount; default: return personsCount; } } } }
|
呼叫方法
1 2 3
| CityInTaiwan.Taipei.getPersonsCount(); //Output:1000000 CityInTaiwan.NewTaipei.getPersonsCount(); //Output:3000000 CityInTaiwan.Taoyuan.getPersonsCount(); //Output:2000000
|