如何为变量分配枚举类型值?

时间:2013-08-02 22:13:47

标签: c# enums compact-framework factory .net-1.1

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

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();
        }
    }
}

我需要在调用NewBeltPrinter()之前设置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;
    }
}

我已经尝试了所有我能想到的东西,而且除了来自编译器的不断谴责之外什么都没有得到回报,这几乎让我误以为是一个笨蛋和一个对不起的流氓。

有人知道我应该用问题代替什么?

4 个答案:

答案 0 :(得分:2)

这样做而不是你的第二个代码块:

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

答案 1 :(得分:1)

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

修改

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

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

答案 2 :(得分:1)

我无法编译到.NET 1.1,但这似乎适用于2.0

PrintUtils.printerChoice = (BeltPrinterType)field.GetValue(null);
编辑:我刚刚意识到这基本上是你的代码中的评论......但是我真的不明白为什么即使在1.1中它也不会起作用

答案 3 :(得分: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");
            }
        }
    }