问题
string liquidClass = string.Empty;
switch (cmbLiquidClass.Text)
{
case "LiquidClass1":
liquidClass = Settings.Default.LiquidClass1;
break;
case "LiquidClass2":
liquidClass = Settings.Default.LiquidClass2;
break;
case "LiquidClass3":
liquidClass = Settings.Default.LiquidClass3;
break;
case "LiquidClass4":
liquidClass = Settings.Default.LiquidClass4;
break;
case "LiquidClass5":
liquidClass = Settings.Default.LiquidClass5;
break;
case "LiquidClass6":
liquidClass = Settings.Default.LiquidClass6;
break;
case "LiquidClass7":
liquidClass = Settings.Default.LiquidClass7;
break;
case "LiquidClass8":
liquidClass = Settings.Default.LiquidClass8;
break;
case "LiquidClass9":
liquidClass = Settings.Default.LiquidClass9;
break;
}
Trying to get in to a local variable the contents of the current class. I can't use a dictionary because of the way strings work (behaving like value types). Is there any way to refactor this so that it doesn't require this many lines to find the chosen liquid class?
回答1:
You can use the indexer that is part of Settings.Default
(tested with .Net 4.0):
var liquidClass = Settings.Default[cmbLiquidClass.Text].ToString();
回答2:
You could convert this to a dictionary easily using some lambda magic.
Dictionary<string, Func<string>> stringsToSettings = new ...
stringsToSettings.Add("LiquidClass1", () => Settings.Default.LiquidClass1);
var liquidClass = stringsToSettings["LiquidClass1"]();
回答3:
I assume you're looking into a way of "converting" a string into a class name.
You could use reflection, which allows you to find a class by name, but it's slow and if you ever decide to rename your class in a future version, your code will not work.
Another way is having at some point of initialization a lookup Dictionary (the curse word!) which binds each class to a string.
来源:https://stackoverflow.com/questions/13868731/how-to-refactor-this-switch-statement