• .NET Framework : 4.7.2
  •        IDE : Visual Studio Community 2019
  •         OS : Windows 10 x64
  •     typesetting : Markdown
  •     

code

using System;

namespace ConsoleApp
{
    public enum Game
    {
        FOOTBALL,
        BASKETBALL,
        PINGPANG
    }
    class Program
    {
        static void Main(string[] args)
        {
            // 枚举类型转为Int
            int n = (int)Game.FOOTBALL;
            Console.WriteLine(n);

            // int转为枚举类型
            Game myFavourite = (Game)1;
            Console.WriteLine(myFavourite);

            // 枚举类型转换成string
            string s = Game.BASKETBALL.ToString();
            Console.WriteLine(s);

            // string转换成枚举
            // 1、数值
            string test0 = "1";
            Game result0 = (Game)Enum.Parse(typeof(Game), test0);
            Console.WriteLine(result0);

            // 2、字符
            string test1 = "BASKETBALL";
            Game result1 = (Game)Enum.Parse(typeof(Game), test1);
            Console.WriteLine(result1);

            // 特殊情况
            // 1、没有匹配的数值----输出10
            string test2 = "10";
            Game result2 = (Game)Enum.Parse(typeof(Game), test2);
            Console.WriteLine(result2);

            // 2、没有匹配的字符串---抛异常
            string test3 = "HELLO";
            Game result3 = (Game)Enum.Parse(typeof(Game), test3);
            Console.WriteLine(result3);


            Console.ReadKey();
        }
    }
}

result

0
BASKETBALL
BASKETBALL
BASKETBALL
BASKETBALL
10

并且抛出异常

C#基础 Enum Parse 枚举与int,string相互转换_Game

resource

  • [文档] docs.microsoft.com/zh-cn/dotnet/csharp
  • [规范] github.com/dotnet/docs/tree/master/docs/standard/design-guidelines
  • [源码] referencesource.microsoft.com
  • [ IDE ] visualstudio.microsoft.com/zh-hans
  • [.NET Core] dotnet.github.io


感恩曾经帮助过 心少朴 的人。
C#优秀,值得学习。.NET Core具有跨平台的能力,值得关注。
Console,WinForm,WPF,ASP.NET,Azure WebJob,WCF,Unity3d,UWP可以适当地了解。
注:此文是自学笔记所生,质量中下等,故要三思而后行。新手到此,不可照搬,应先研究其理象数,待能变通之时,自然跳出深坑。

欢迎关注微信公众号:悟为生心

C#基础 Enum Parse 枚举与int,string相互转换_枚举类型_02