我将使用Enum做什么? [英] What would I use an Enum for?

查看:62
本文介绍了我将使用Enum做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经声明了一个枚举类型,给它分配了一个变量现在我将其写入控制台.那么,枚举类型在实际应用中有什么用?

I've declared an enum type, assigned a variable to it and now I am writing it to the console. So what use does an enum type have in a real world application?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
   class Enum
{
    enum cars
    {
        Toyota, Nissan, Ferrari, Lamborghini
    }
}
class Program
{
    enum cars
    {
        Toyota, Nissan, Ferrari, Lamborghini
    }
    static void Main(string[] args)
    {
        int a = (int)cars.Ferrari;
        Console.WriteLine(a);
    }
}
}

推荐答案

每当过程接受一组有限的变量时,请考虑使用枚举.枚举使代码更清晰,可读性更好,尤其是在使用有意义的名称时.

Whenever a procedure accepts a limited set of variables, consider using an enumeration. Enumerations make for clearer and more readable code, particularly when meaningful names are used.

使用枚举的好处包括:

  • 减少因转置或错误输入数字而导致的错误.

  • Reduces errors caused by transposing or mistyping numbers.

使将来轻松更改值变得容易.

Makes it easy to change values in the future.

使代码更易于阅读,这意味着错误的可能性较小会爬进去的.

Makes code easier to read, which means it is less likely that errors will creep into it.

确保向前兼容.使用枚举,您的代码更少如果将来有人更改值,可能会失败对应于会员名.

Ensures forward compatibility. With enumerations, your code is less likely to fail if in the future someone changes the values corresponding to the member names.

ref: MSDN

这篇关于我将使用Enum做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆