我有一些工厂代码根据代表枚举的类成员的值创建对象:
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;
}
}
我已经尝试了我能想到的一切,但得到的回报只是编译器不断的谴责,这几乎是把我当作一个无赖和一个可悲的流氓。
有人知道我应该用什么代替问号吗?