• C# 为枚举创建新方法


    可以使用扩展方法添加特定于某个特定枚举类型的功能。

    示例
    在下面的示例中,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 类还包含一个动态更新的静态变量,并且扩展方法的返回值反映了该变量的当前值。  这表明在幕后,将在定义扩展方法的静态类上直接调用这些方法。  

  • 相关阅读:
    记一次手工端假设之旅
    宝塔面板相关笔记
    linux ubuntu centos 相关笔记
    问题解决笔记,Restarting network (via systemctl):: Job for network.service failed. ...
    Ubuntu中使用yum
    小说爬取 python + urllib + lxml
    wsgiref错误解决笔记 "write() argument must be a bytes instance"
    个人作品导航:
    django基础一
    前端小知识(5)--响应式页面实现
  • 原文地址:https://www.cnblogs.com/rinack/p/5695351.html
Copyright © 2020-2023  润新知