zoukankan      html  css  js  c++  java
  • C#语言使用技巧枚举

    • 枚举

    例如有一个动物枚举

    public enum AnimalEnum { Dog =12, Cat = 10 }
    • Enum Convert To String
    public void ConvertToString(AnimalEnum animal) 
    {
       animal.ToString();//Example: animal == AnimalEnum.Dog => "Dog"
    }
    • Enum To Int
    public void ConvertToInt(AnimalEnum animal) 
    { 
      int i = (int)animal;//Example: animal == AnimalEnum.Dog => 12
    
    }
    • 遍历枚举(反射 + Enum.GetNames())
    1. 字符串格式
      public void Enumerate()
      {
           Type type = typeof(AnimalEnum);
      
           string[] names = Enum.GetNames(type);
      
           foreach (string str in names)
          {
                Console.WriteLine(str);    
          }
      }
    2. 枚举格式
      public void Enumerate()
      {
           Array array = Enum.GetValues(typeof(AnimalEnum));
      
      
           foreach (AnimalEnum ae in array)
          {
                Console.WriteLine(ae.ToString());
          }
      }
    • Enum.Fotmat  格式化输出
    public static string Format(
        Type enumType,
        Object value,
        string format
    )
    Enum.Format(
    typeof(AnimalEnum),AnimalEnum.Dog,format);
    • Format
    1. d or D   十进制输出
    2. x or X    十六进制输出
    3. g or G   字符串格式输出
    4. f   or F   字符串格式输出


    判断枚举是否定义

    public bool IsDefined(int num)
    {
         return Enum.IsDefined(typeof(AnimalEnum),num);
    }
    
    public bool IsDefined(string name)
    {
          return Enum.IsDefined(typeof(AnimalEnum),num); 
    }
  • 相关阅读:
    vpp编写plugin
    vrf 命令
    vxlan + 多个vrf
    dpdk helloworld
    Go函数高级
    Go_defer
    Go递归函数
    Go作用域
    Go函数
    Go字符串
  • 原文地址:https://www.cnblogs.com/WilsonPan/p/2533257.html
Copyright © 2011-2022 走看看