C# 枚举 VS 静态类(普通和带字符串值)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13696098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:27:42  来源:igfitidea点击:

Enum VS Static Class (Normal and With String Values)

c#javaandroidwindows-phone-7

提问by Akhil Sekharan

I have been developing for windows mobile and android for sometime. And I'm confused about these two concepts.

我一直在为 windows mobile 和 android 开发一段时间。我对这两个概念感到困惑。

Let's say I want to make decision based on some the user's device Screen Size. So I'll expect so predefined values. I could use a switch statement for handling my logic. But I'm not sure whether I should use Enum of a Static Class for this purpose. Which one is a better approach. I can do my logic in these two different ways. Which one is the correct approach? I'm confused. And is it possible for me to use String values also?Because currently I'm sticking with classes, I need to update to use all enums. So How about changing my Class to String Enum? Any way. Thanks.

假设我想根据用户的设备屏幕尺寸做出决定。所以我期待如此预定义的值。我可以使用 switch 语句来处理我的逻辑。但我不确定是否应该为此使用静态类的枚举。哪个是更好的方法。我可以用这两种不同的方式来做我的逻辑。哪一种是正确的做法?我糊涂了。我也可以使用字符串值吗?因为目前我坚持使用类,所以我需要更新以使用所有枚举。那么如何将我的 Class 更改为 String Enum?反正。谢谢。

Using Enum

使用枚举

//My predefined values
public enum ScreenSizeEnum
{
    Small, Medium, Large, XLarge,
}
//Handling Logic
private void SetScreenSize(ScreenSizeEnum Screen)
{
    switch (Screen)
    {
        case ScreenSizeEnum.Large:
            //Do Logic
            break;
        case ScreenSizeEnum.Small:
            //Do Logic
            break;
    }
}

Using Class

使用类

//My predefined values
public class ScreenSizeClass
{
    public const int Small = 0;
    public const int Medium = 1;
    public const int Large = 2;
    public const int XLarge = 3;
}
//Handling Logic
private void SetScreenSize(int Screen)
{
    switch (Screen)
    {
        case ScreenSizeClass.Large:
            //Do Logic
            break;
        case ScreenSizeClass.Small:
            //Do Logic
            break;
    }
}

采纳答案by horgh

From Enumeration Types (C# Programming Guide):

来自枚举类型(C# 编程指南)

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 following are advantages of using an enum instead of a numeric type:

  1. You clearly specify for client code which values are valid for the variable.

  2. In Visual Studio, IntelliSense lists the defined values.

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

以下是使用枚举而不是数字类型的优点:

  1. 您为客户端代码明确指定哪些值对变量有效。

  2. 在 Visual Studio 中,IntelliSense 列出了定义的值。

So if you pass enum, it is strongly typed, so you automatically get control over what you can pass into a method.

因此,如果传递enum,它是强类型的,因此您可以自动控制可以传递给方法的内容。

ScreenSizeEnum size = ScreenSizeEnum.Medium;
SetScreenSize(size); 

When using constor staticfields you definetely need to check whether the passed intvalue is taken from the expected diapason.

使用conststatic字段时,您肯定需要检查传递的int值是否取自预期的音调。

int somevalue = ...;//anything
SetScreenSize(somevalue); //compiles

private void SetScreenSize(int Screen)
{
    switch (Screen)
    {
        case ScreenSizeClass.Large:
            //Do Logic
            break;
        case ScreenSizeClass.Small:
            //Do Logic
            break;
        default: 
            // something else, what to do??
            break;
    }
}


Based on comments:

基于评论:

If it's necessary to check, whether some intis defined in enum, one can do something like this:

如果有必要检查 some 是否int在 中定义enum,可以执行以下操作:

int somevallue = 0;
if(Enum.IsDefined(typeof(ScreenSizeEnum), somevallue))
{
    //it's ok
}

Or an extension method:

或扩展方法:

public static T GetEnumValue<T>(this string value) where T : struct
{
    Type t = typeof(T);
    if (!t.IsEnum)
        throw new Exception("T must be an enum");
    else
    {
        T result;
        if (Enum.TryParse<T>(value, out result))
            return result;
        else
            return default(T);
    }
}

which could be used

可以使用

int somevalue = 1;
ScreenSizeEnum size = somevalue.GetEnumValue<ScreenSizeEnum>();


As for the string(based on OP's edited question):

至于string(基于 OP 编辑​​的问题):

From enum (C# Reference):

来自枚举(C# 参考)

The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.

认可的枚举类型是 byte、sbyte、short、ushort、int、uint、long 或 ulong。

So you cannot have an enum of strings. But you can use names from enums, as ToStringmethod returns the name, not the value of the enum.

所以你不能有一个字符串枚举。但是您可以使用枚举中的名称,因为ToString方法返回名称,而不是枚举的值。

ScreenSizeEnum.Small.ToString(); //Small

So you can have another extension method on strings:

所以你可以在字符串上有另一个扩展方法:

public static T GetEnumValue<T>(this string value) where T : struct
{
    Type t = typeof(T);
    if (!t.IsEnum)
        throw new Exception("T must be an enum");
    else
    {
        if (Enum.IsDefined(t, value))
            return (T)Enum.Parse(t, value);
        else
            return default(T);
    }
}

So that

以便

int i = (int)ScreenSizeEnum.Small;
string str = ScreenSizeEnum.Small.ToString();
ScreenSizeEnum isize = i.GetEnumValue<ScreenSizeEnum>();//ScreenSizeEnum.Small
ScreenSizeEnum strsize = str.GetEnumValue<ScreenSizeEnum>();//ScreenSizeEnum.Small

回答by Zdravko Danev

This is precisely what enums are there for. Not that you can't use the static class with the constants, but enum is by far cleaner...

这正是枚举的用途。并不是说您不能将静态类与常量一起使用,而是枚举要干净得多......

回答by Nishant Shah

enums are basically used when you want a variable or parameter to have value from a fixed set of possible constants. You can replace enums with class with a set of static final int constants. But using enums is more flexible & readable appraoch over the later one.

当您希望变量或参数具有来自一组固定的可能常量的值时,基本上会使用枚举。您可以使用一组静态最终 int 常量用类替换枚举。但是使用枚举比后一种更灵活和可读。

回答by Herman Van Der Blom

A class can be very handy if you want more as the enumerator only. If you want to implement several Get... functions that can return other things that you need.

如果您只想要更多作为枚举器,类会非常方便。如果你想实现几个可以返回你需要的其他东西的 Get... 函数。

My example is that I have a class of some type but there is a related other type that I need to.

我的例子是我有一个某种类型的类,但我需要一个相关的其他类型。