如何将枚举类型值分配给变量

本文关键字:分配 变量 类型 枚举 | 更新日期: 2023-09-27 18:26:15

我有一些工厂代码,它根据表示枚举的类成员的值创建对象:

public enum BeltPrinterType
{
    None,
    ZebraQL220,
    ONiel
    // add more as needed
}
public static BeltPrinterType printerChoice = BeltPrinterType.None;
public class BeltPrinterFactory : IBeltPrinterFactory
{
    // http://stackoverflow.com/questions/17955040/how-can-i-return-none-as-a-default-case-from-a-factory?noredirect=1#comment26241733_17955040
    public IBeltPrinter NewBeltPrinter()
    {
        switch (printerChoice)
        {
            case BeltPrinterType.ZebraQL220: 
                return new ZebraQL220Printer();
            case BeltPrinterType.ONiel: 
                return new ONielPrinter();
            default: 
                return new None();
        }
    }
}

在调用NewBeltPinter()之前,我需要设置printerChoice的值,也就是说,如果它已经从默认的"None"值更改。因此,我试图根据字符串表示来分配该值,但这次尝试已经达到了众所周知的不连续点:

string currentPrinter = AppSettings.ReadSettingsVal("beltprinter");
Type type = typeof(PrintUtils.BeltPrinterType);
foreach (FieldInfo field in type.GetFields(BindingFlags.Static | BindingFlags.Public))
{
    string display = field.GetValue(null).ToString();
    if (currentPrinter == display)
    {
        //PrintUtils.printerChoice = (type)field.GetValue(null);
        PrintUtils.printerChoice = ??? what now ???
        break;
    }
}

我已经试过了我能想到的一切,但得到的回报只是编译器的不断斥责,这几乎把我误解为一个无赖和一个可怜的流氓。

有人知道我应该用什么来代替问号吗?

如何将枚举类型值分配给变量

你的第二个代码块:

PrintUtils.printerChoice = (PrintUtils.BeltPrinterType)
    Enum.Parse(typeof(PrintUtils.BeltPrinterType),
               AppSettings.ReadSettingsVal("beltprinter"));

使用Enum.Parse将字符串转换为枚举值。(或者Enum.TryParse,如果它没有解析,则尝试在不引发异常的情况下执行此操作)

编辑

如果您没有可用的Enum.Parse,那么您将不得不自己进行转换:

switch (stringValue)
{
    case "BeltPrinterType.ONiel": enumValue = BeltPrinterType.ONiel; break;
    ...etc...
}

我无法编译到.NET 1.1,但这似乎在2.0 中有效

PrintUtils.printerChoice = (BeltPrinterType)field.GetValue(null);

编辑:我刚刚意识到这基本上是你代码中的一个注释。。。但是,是的,我真的不明白为什么这在1.1 中也不起作用

来自智能设备框架1.x代码库:

    public static object Parse(System.Type enumType, string value, bool ignoreCase)
    {
        //throw an exception on null value
        if(value.TrimEnd(' ')=="")
        {
            throw new ArgumentException("value is either an empty string ('"'") or only contains white space.");
        }
        else
        {
            //type must be a derivative of enum
            if(enumType.BaseType==Type.GetType("System.Enum"))
            {
                //remove all spaces
                string[] memberNames = value.Replace(" ","").Split(',');
                //collect the results
                //we are cheating and using a long regardless of the underlying type of the enum
                //this is so we can use ordinary operators to add up each value
                //I suspect there is a more efficient way of doing this - I will update the code if there is
                long returnVal = 0;
                //for each of the members, add numerical value to returnVal
                foreach(string thisMember in memberNames)
                {
                    //skip this string segment if blank
                    if(thisMember!="")
                    {
                        try
                        {
                            if(ignoreCase)
                            {
                                returnVal += (long)Convert.ChangeType(enumType.GetField(thisMember, BindingFlags.Public | BindingFlags.Static | BindingFlags.IgnoreCase).GetValue(null),returnVal.GetType(), null);
                            }
                            else
                            {
                                returnVal += (long)Convert.ChangeType(enumType.GetField(thisMember, BindingFlags.Public | BindingFlags.Static).GetValue(null),returnVal.GetType(), null);
                            }
                        }
                        catch
                        {
                            try
                            {
                                //try getting the numeric value supplied and converting it
                                returnVal += (long)Convert.ChangeType(System.Enum.ToObject(enumType, Convert.ChangeType(thisMember, System.Enum.GetUnderlyingType(enumType), null)),typeof(long),null);
                            }
                            catch
                            {
                                throw new ArgumentException("value is a name, but not one of the named constants defined for the enumeration.");
                            }
                            //
                        }
                    }
                }

                //return the total converted back to the correct enum type
                return System.Enum.ToObject(enumType, returnVal);
            }
            else
            {
                //the type supplied does not derive from enum
                throw new ArgumentException("enumType parameter is not an System.Enum");
            }
        }
    }