C#,入门教程(11)——枚举(Enum)的基础知识和高级应用

上一篇:

C#,入门教程(10)——常量、变量与命名规则的基础知识icon-default.png?t=N7T8https://blog.csdn.net/beijinghorn/article/details/123913570

不会枚举,就不会编程!

枚举 = 一个有组织的常量系列

比如:一个星期每一天的名字,周一、周二。。。周日。

所有成系列的常量都应该用枚举方式加以定义与使用。

一、枚举的定义

C#用 enum 定义枚举。

每个项都被自动赋予了一个(整数类型)值。对于整数类型,项值是递增的。默认是从 0 开始的,也就是项 1 的值是 0、项 2 的值是 1。如果不需要系统自动为项指定值,也可以直接为其赋一个(数)值。每个没有指定值的项,它的初始值都是上一个项的值 +1。可以任意指定某项为特定的值。拗口吧?看文字学不到的,多看看代码就能理解了。

1、基本格式

// 完整方式
访问修饰符 enum 枚举名字 : 数据类型(可无)
{
     枚举项 = 初值(可无),
}

// 实例
public enum GradeName : int
{
    幼儿园 = 0,
    小学,
    初中,
    高中,
    大学 = 10,
    硕士,
    博士
}

2、简约模式


// 简约模式(默认数据类型int)
// 第一项,默认从0开始
public enum GradeName
{
    Undefined = -1,
    幼儿园,
    小学,
    初中,
    高中,
    大学,
    硕士,
    博士
}

二、枚举的使用

定义好的枚举,类似于一种数据类型,用起来与 int 、double 差不多。

// 类
public class StudentInfo
{
    public GradeTitle Grade { get; set; } = GradeTitle.Undefined;
}

// 幼儿园毕业?毕业证呢?
// 拿不出来?那你没有最低学历!
if(firstStudent.Grade == GradeTitle.幼儿园)
{
    ;
}

又:所有枚举的第一个项一定是 Undefined !!!

枚举很简单,用好不简单。

三、枚举与字符串的对照方法

有些情况下,为了代码或结果的可阅读性,期望将 枚举 与 字符串对照起来。

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection;

namespace DataBeginner
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterScreen;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("2 is " + EnumDescription(EnglishNumbers.Two));

            webBrowser1.DocumentText = sb.ToString();
        }

        /// <summary>
        /// 利用反射机制,从枚举数值获取其文本描述字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string EnumDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }
    }

    public enum EnglishNumbers
    {
        [Description("One")] 
        One = 1,
        [Description("Two")] 
        Two = 2,
        [Description("Three")] 
        Three = 3,
        [Description("Four")] 
        Four = 4,
        [Description("Five")] 
        Five
    }
}

下一篇:

C#,入门教程(12)——数组及数组使用的基础知识icon-default.png?t=N7T8https://blog.csdn.net/beijinghorn/article/details/123918227

猜你喜欢

转载自blog.csdn.net/beijinghorn/article/details/123917587