扩展方法
class Program { static void Main(string[] args) { //扩展方法 语法糖 谨慎使用 int[] ints = { 10, 45, 15, 39, 21, 26 }; var result = ints.OrderBy(g => g); foreach (int v in result) { Console.WriteLine(v); } string s = "This is Jikexueyuan c# tutorial"; Console.WriteLine("the string have {0} words", s.wordCount()); Console.ReadLine(); } } public static class StringExtension { public static int wordCount(this string Str) { return Str.Split(new char[] { ' ', ',', '.', '!' }, StringSplitOptions.RemoveEmptyEntries).Length; } }
枚举上的实现
public enum Grades { F = 0, D = 1, C = 2, B = 3, A = 4 }; class Program { static void Main(string[] args) { var g1 = Grades.D; var g2 = Grades.F; var g3 = Grades.A; Console.WriteLine("1 {0} a passing grade", g1.Passing() ? "is" : "is not"); Console.WriteLine("2 {0} a passing grade", g2.Passing() ? "is" : "is not"); Console.WriteLine("3 {0} a passing grade", g3.Passing() ? "is" : "is not"); EnumExtension.miniPassing = Grades.C; Console.WriteLine("1 {0} a passing grade", g1.Passing() ? "is" : "is not"); Console.WriteLine("2 {0} a passing grade", g2.Passing() ? "is" : "is not"); Console.WriteLine("3 {0} a passing grade", g3.Passing() ? "is" : "is not"); Console.ReadLine(); } } public static class EnumExtension { public static Grades miniPassing = Grades.D; public static bool Passing(this Grades grades) { return grades >= miniPassing; } }