Declaration and use of c# enumeration types

Time:2021-10-12
catalogue
  • preface
    • Related introduction
    • 1、 Enumeration declaration
    • 2、 Declaration location
    • 3、 Enumeration use
  • summary

    preface

    Learn to record the declaration and use of enumeration. Enumeration can be used to standardize development

    The project name of the code in this article isProject1C#The class name isClass1

    Related introduction

    Microsoft official c# function document

    1、 Enumeration declaration

    Declaration method:Enum [enum name] {value 1, value 2,..., value n}

    For the last value, the comma can be written or not. For text, the value does not need to be enclosed in quotation marks

    enum Gender
    {
        Male,
        female
    }

    2、 Declaration location

    Can be declared innamespaceIn command space

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace Project1
    {
        enum Gender
        {
            Male,
            female
        }
        class Class1
        {
            static void Main(string[] args)
            {
            }
        }
    }

    You can alsoClassClass, cannot be declared inside a method (includingMainFunction)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace Project1
    {
        class Class1
        {
            enum Gender
            {
                Male,
                female
            }
            static void Main(string[] args)
            {
            }
        }
    }

    3、 Enumeration use

    usage method:[enum name] [variable name] = [enum name]. [value]After entering the enumeration name and decimal point, you can useTabKey displays the available values

    在这里插入图片描述

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    namespace Project1
    {
        class Class1
        {
            enum Gender
            {
                Male,
                female
            }
            static void Main(string[] args)
            {
                Gender sex = Gender.female;
                Console.WriteLine(sex);
                Console.ReadKey();
            }
        }
    }

    When using enumeration, you canClassClasses and methods, but not in namespacein

    在这里插入图片描述

    summary

    That’s all for this article. I hope it will help you more, and I hope you can pay more attention to more content of developeppaer!