枚举的主要用途是什么?

发布于 2024-09-15 13:22:47 字数 92 浏览 8 评论 0原文

C#中枚举的主要用途是什么?

编辑:- 假设我想将字符串变量与任何枚举项进行比较,那么我如何在 C# 中做到这一点?

What is main use of Enumeration in c#?

Edited:-
suppose I want to compare the string variable with the any enumeration item then how i can do this in c# ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

深者入戏 2024-09-22 13:22:48

MSDN 中的定义是一个很好的起点。

枚举类型(也称为
枚举或枚举)提供了
定义一组命名的有效方法
积分常数可能是
分配给一个变量。

这样做的主要好处是可以以一致、富有表现力和类型安全的方式引用常量。

以这个非常简单的带有构造函数的 Employee 类为例:

您可以这样做:

public class Employee
{
    private string _sex;

    public Employee(string sex)
    {
       _sex = sex;
    }
}

但是现在您依赖用户为该字符串输入正确的值。

使用枚举,您可以:

public enum Sex
{
    Male = 10,
    Female = 20
}

public class Employee
{
    private Sex _sex;

    public Employee(Sex sex)
    {
       _sex = sex;
    }
}    

这突然允许 Employee 类的使用者更轻松地使用它:

Employee employee = new Employee("Male");

变成:

Employee employee = new Employee(Sex.Male);

The definition in MSDN is a good place to start.

An enumeration type (also named an
enumeration or an enum) provides an
efficient way to define a set of named
integral constants that may be
assigned to a variable.

The main benefit of this is that constants can be referred to in a consistent, expressive and type safe way.

Take for example this very simple Employee class with a constructor:

You could do it like this:

public class Employee
{
    private string _sex;

    public Employee(string sex)
    {
       _sex = sex;
    }
}

But now you are relying upon users to enter just the right value for that string.

Using enums, you can instead have:

public enum Sex
{
    Male = 10,
    Female = 20
}

public class Employee
{
    private Sex _sex;

    public Employee(Sex sex)
    {
       _sex = sex;
    }
}    

This suddenly allows consumers of the Employee class to use it much more easily:

Employee employee = new Employee("Male");

Becomes:

Employee employee = new Employee(Sex.Male);
迷荒 2024-09-22 13:22:48

通常你会发现你有一些东西——数据、分类等等——最好将其表达为可以用整数表示的几个离散状态之一。典型的例子是一年中的几个月。我们希望一年中的月份既可以表示为字符串(“2010 年 8 月 19 日”),也可以表示为数字(“8/19/2010”)。 Enum 提供了一种为一组整数分配名称的简洁方法,因此我们可以使用简单的整数循环来移动月份。

Often you find you have something - data, a classification, whatever - which is best expressed as one of several discrete states which can be represented with integers. The classic example is months of the year. We would like the months of the year to be representable as both strings ("August 19, 2010") and as numbers ("8/19/2010"). Enum provides a concise way to assign names to a bunch of integers, so we can use simple loops through integers to move through months.

浅暮の光 2024-09-22 13:22:48

枚举是强类型常量。枚举是一组特殊的命名值,它们全部映射到一组数字,通常是整数。当您希望能够在一组常量值之间进行选择时,它们会派上用场,并且每个可能的值都与数字相关,因此它们可以在多种情况下使用。正如您将在我们的示例中看到的,枚举是在我们的命名空间内的类之上定义的。这意味着我们可以使用同一命名空间中所有类的枚举。

using System;

namespace ConsoleApplication1
{
    public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }

    class Program
    {
        static void Main(string[] args)
        {
            Days day = Days.Monday;
            Console.WriteLine((int)day);
            Console.ReadLine();
        }
    }
}

Enums are strongly typed constants. Enumerations are special sets of named values which all maps to a set of numbers, usually integers. They come in handy when you wish to be able to choose between a set of constant values, and with each possible value relating to a number, they can be used in a wide range of situations. As you will see in our example, enumerations are defined above classes, inside our namespace. This means we can use enumerations from all classes within the same namespace.

using System;

namespace ConsoleApplication1
{
    public enum Days { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday }

    class Program
    {
        static void Main(string[] args)
        {
            Days day = Days.Monday;
            Console.WriteLine((int)day);
            Console.ReadLine();
        }
    }
}
故事还在继续 2024-09-22 13:22:48

枚举(Enum)是一种变量类型。我们可以在 C、C# 和许多其他语言中找到这种变量类型。
Enum 的基本思想是,如果我们有一组整数类型的变量(默认情况下),那么不要使用太多 int 值,只需使用 Enum。这是有效的方法。假设你想写彩虹色,那么你可以这样写:

const int Red = 1;
const int Orange = 2;
const int Yellow = 3;
const int Green = 4;
const int Blue = 5;
const int Indigo = 6;
const int Violet = 7;

在这里你可以看到太多的 int 声明。如果您或您的程序错误地更改了任何整数变量的值,即 Violet = 115 而不是 7,那么调试将非常困难。

所以,Enum 来了。您可以为任何一组整数类型的变量定义 Enum。对于 Enum,您可以这样编写代码:

enum rainBowColors
{
 red=1,
 orange=2,
 yellow=3,
 green,
 blue=8,
 indigo=8,
 violet=16) 
}; 

rainBowColors 是一种类型,只有相同类型的其他变量才能分配给它。在 C#/C++ 中,您需要类型转换,而在 C 中,您不需要类型转换。

现在,如果你想声明一个 rainBowColors 类型的变量,那么在 C

enum rainBowColors variableOne = red;

和 C# / C++ 中你可以这样做:

rainBowColors variableOne = red;

Enumeration (Enum) is a variable type. We can find this variable type in C, C# and many other languages.
Basic Idea for Enum is that if we have a group of variable of integer type (by default) then instead of using too much int values just use a Enum. It is efficient way. Let suppose you want to write rainbow colours then you may write like this:

const int Red = 1;
const int Orange = 2;
const int Yellow = 3;
const int Green = 4;
const int Blue = 5;
const int Indigo = 6;
const int Violet = 7;

here you can see that too many int declarations. If you or your program by mistake change the value of any integer varialbe i.e. Violet = 115 instead of 7 then it will very hard to debug.

So, here comes Enum. You can define Enum for any group of variables type integers. For Enum you may write your code like this:

enum rainBowColors
{
 red=1,
 orange=2,
 yellow=3,
 green,
 blue=8,
 indigo=8,
 violet=16) 
}; 

rainBowColors is a type and only other variables of the same type can be assigned to this. In C#/C++ you need to type casting while in C you do not to type cast.

Now, if you want to declare a variable of type rainBowColors then in C

enum rainBowColors variableOne = red;

And in C# / C++ you can do this as:

rainBowColors variableOne = red;
染柒℉ 2024-09-22 13:22:48

C#中的枚举有两种含义。

枚举(名词)是一组命名值。示例:

public enum Result {
  True,
  False,
  FileNotFound
}

枚举(动词 enumerate 的名词形式)是指单步执行集合中的项目。

IEnumerable 接口由提供枚举功能的类使用。数组就是此类的一个简单示例。另一个示例是 LINQ 如何使用它以可枚举集合的形式返回结果。

编辑:

如果要将字符串与枚举值进行比较,则必须将字符串解析为枚举类型:

if ((Result)Enum.Parse(typeof(Result), theString) == Result.True) ...

或将枚举值转换为字符串:(

if (theString == Result.True.ToString()) ...

请注意如何比较这些值,具体取决于您是否想要区分大小写是否匹配。)

如果要枚举集合并查找字符串,可以使用 foreach 命令:

foreach (string s in theCollection) {
  if (s == theString) {
    // found
  }
}

There are two meanings of enumeration in C#.

An enumeration (noun) is a set of named values. Example:

public enum Result {
  True,
  False,
  FileNotFound
}

Enumeration (noun form of the verb enumerate) is when you step through the items in a collection.

The IEnumerable<T> interface is used by classes that provide the ability to be enumerated. An array is a simple example of such a class. Another example is how LINQ uses it to return results as enumerable collections.

Edit:

If you want to compare a string to an enum value, you either have to parse the string to the enum type:

if ((Result)Enum.Parse(typeof(Result), theString) == Result.True) ...

or convert the enum value to a string:

if (theString == Result.True.ToString()) ...

(Be careful how you compare the values, depending on whether you want a case sensetive match or not.)

If you want to enumerate a collection and look for a string, you can use the foreach command:

foreach (string s in theCollection) {
  if (s == theString) {
    // found
  }
}
死开点丶别碍眼 2024-09-22 13:22:48

使用 Enum 的另一个优点是,如果需要更改任何整数值,我们只需更改 Enum 定义,就可以避免到处更改代码。

Another advantage of using Enum is that in case of any of the integer value needs to be changed, we need to change only Enum definition and we can avoid changing code all over the place.

记忆里有你的影子 2024-09-22 13:22:48

枚举类型(也称为枚举或枚举)提供了一种有效的方法来定义一组可分配给变量的命名整型常量。

http://msdn.microsoft.com/en-us/library/cc138362。 ASPX

An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable.

http://msdn.microsoft.com/en-us/library/cc138362.aspx

格子衫的從容 2024-09-22 13:22:48

枚举 (ENUM)

枚举是一种值类型,具有一组相关的命名常量,通常称为枚举器列表。 enum 关键字用于声明枚举。它是一种原始数据类型,由用户定义。

枚举类型可以是整数(float、int、byte、double 等)。但如果你在 int 旁边使用它,它就必须被强制转换。

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
enum Months : byte { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }; 

Enumeration (ENUM)

An enum is a value type with a set of related named constants often referred to as an enumerator list. The enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.

Enums type can be integer (float, int, byte, double etc.). But if you used beside int it has to be cast.

enum Days { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday };
enum Months : byte { Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec }; 
绻影浮沉 2024-09-22 13:22:48

让我们举个例子,我们在一个类中取正常常数,例如
整数a=10;

我们错误地为同一个类中的变量分配了新值,例如
a=20;
那么当我们想要访问它们时,我们就会得到错误的数据。
枚举提供了访问常量的安全方式。

此外,如果我们在一个类中有很多字段常量,如果我们想在类中使用它们,我们就必须记住它们。
但是枚举包含一组相关名称常量,如果我们想访问常量那么我们只需要记住枚举名称。

Lets Take an Example we are taking normal constant in a class like
int a=10;

by mistakely we assign new value to that variable in that same class like
a=20;
then we will get wrong data when we want access them.
enum provide secure way of accessing constant.

Also if we have many feild constant in a class we had to memorize them if we want to use them in a class.
but enum contains group of related name constant, if we want to access the constant then only we had to memorize enum name.

天煞孤星 2024-09-22 13:22:48

根据我的经验,枚举在非常特殊的情况下有效,并且当您绝对需要在应用程序中维护它时应该使用枚举。当您与多个开发人员一起工作并且一些新开发人员加入一个项目并且可以向应用程序添加枚举时,枚举会出现问题,所有构建都没有错误,但随后您有另一个全栈开发人员在查找中维护相同的列表表以不同的顺序。 Kaboom!!!

即使不是故意的,也被那个人烧伤了很多次。根据经验,不要在应用程序中维护超过 5 或 6 个项目的枚举列表。如果更高,您不妨将它们存储在您选择的数据库的查找表中。

Enumerations in my experience have worked in very specific cases and should be used when you absolutely need to maintain this in your application. Problems come into play with Enums when you are working with multiple developers and some new developer comes on to a project and can adds a enum to the application no errors everything builds but then you have another full stack developer that maintains this same list in a lookup table in a different order. Kaboom!!!!

Burned way to many times with that one even if not intentional. Rule of thumb don't maintain a list of enums in a app over 5 or 6 items. If higher you might as well store them in a lookup table in the DB of your choice.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文