可以使用扩展方法添加特定于某个特定枚举类型的功能。
示例
在下面的示例中,Grades 枚举表示学生可能在班里收到的字母等级分。该示例将一个名为 Passing 的扩展方法添加到 Grades 类型中,
以便该类型的每个实例现在都“知道”它是否表示合格的等级分。
using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace EnumExtension { // Define an extension method in a non-nested static class. public static class Extensions { public static Grades minPassing = Grades.D; public static bool Passing(this Grades grade) { return grade >= minPassing; } } public enum Grades { F = 0, D=1, C=2, B=3, A=4 }; class Program { static void Main(string[] args) { Grades g1 = Grades.D; Grades g2 = Grades.F; Console.WriteLine("First {0} a passing grade.", g1.Passing() ? "is" : "is not"); Console.WriteLine("Second {0} a passing grade.", g2.Passing() ? "is" : "is not"); Extensions.minPassing = Grades.C; Console.WriteLine(" Raising the bar! "); Console.WriteLine("First {0} a passing grade.", g1.Passing() ? "is" : "is not"); Console.WriteLine("Second {0} a passing grade.", g2.Passing() ? "is" : "is not"); } } } /* Output: First is a passing grade. Second is not a passing grade. Raising the bar! First is not a passing grade. Second is not a passing grade. */
请注意,Extensions 类还包含一个动态更新的静态变量,并且扩展方法的返回值反映了该变量的当前值。 这表明在幕后,将在定义扩展方法的静态类上直接调用这些方法。