我的应用程序中有ENUM和扩展,我这样使用:
public enum CO
{
Random = 0,
FirstToLast = 1,
LastToFirst = 2,
}
public static partial class Extensions
{
public static string Text(this CO cardOrder)
{
switch (cardOrder)
{
case CO.Random: return "Random";
case CO.FirstToLast: return "1, 2, 3";
case CO.LastToFirst: return "3, 2, 1";
}
return "";
}
}
在代码中,我设置了switch语句来决定更新数据库:
switch (segControlCardOrder.SelectedValue)
{
case "Random":
App.DB.UpdateIntSetting(SET.Co, (int)CO.Random);
break;
case "1, 2, 3":
App.DB.UpdateIntSetting(SET.Co, (int)CO.FirstToLast);
break;
case "3, 2, 1":
App.DB.UpdateIntSetting(SET.Co, (int)CO.LastToFirst);
break;
}
有没有一种方法可以避免使用switch语句,只根据ENUM的值调用UpdateIntSettings?
您还可以添加另一种方式的扩展方法(从字符串到枚举(。然后你可以在你的声明中使用方法:
public static CO CardOrder(this string cardOrder)
{
switch (cardOrder)
{
case "Radom": return CO.Random;
case "1, 2, 3": return CO.FirstToLast;
case "3, 2, 1": return CO.LastToFirst;
}
throw new ArgumentException(string.Format($"{cardOrder} is not a CO representation"));
}
简单使用:
App.DB.UpdateIntSetting(SET.Co, (int)segControlCardOrder.SelectedValue.CardOrder());
您可以将Dictionary<string, CO>
初始化为类的私有或静态成员:
dict.Add("Random", CO.Random);
dict.Add("1, 2, 3", CO.FirstToLast);
dict.Add("3, 2, 1", CO.LastToFirst);
最后做:
App.DB.UpdateIntSetting(Set.CO, (int)dict[segControlCardOrder.SelectedValue]);
是的,但效率较低。您可以使用值的字典,如:
var dict = new Dictionary<string, CO> { ["Random"] = CO.Random, ["1, 2, 3"] = CO.FirstToLast, ["3, 2, 1"] = CO.LastToFirst };
App.DB.UpdateIntSetting(SET.Co, (int)dict[segControlCardOrder.SelectedValue]);
或者只需在变量中将值设置为using,然后将其传递给方法。我更喜欢最后一种方式。