枚举VS静态类(正常和带字符串值)

问题描述 投票:8回答:4

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

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

使用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;
    }
}

使用类

//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;
    }
}
c# java android windows-phone-7
4个回答
7
投票

来自Enumeration Types (C# Programming Guide)

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

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

  1. 您明确指定客户端代码哪些值对变量有效。
  2. 在Visual Studio中,IntelliSense列出已定义的值。

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

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

当使用qazxsw poi或qazxsw poi字段时,你肯定需要检查传递的const值是否取自预期的diapason。

static

基于评论:

如果有必要检查,是否在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; } } ,可以这样做:

int

或者扩展方法:

enum

可以使用

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

至于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); } } (基于OP的编辑问题):

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

枚举的已批准类型是byte,sbyte,short,ushort,int,uint,long或ulong。

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

enum (C# Reference)

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

ToString

以便

ScreenSizeEnum.Small.ToString(); //Small

8
投票

这正是enums的用途。并不是说你不能将静态类与常量一起使用,但枚举更清晰......


1
投票

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


0
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.