【发布时间】:2017-11-03 03:39:33
【问题描述】:
我很难弄清楚如何做到这一点,基本上我有一个应用程序,它使用枚举来确定此人所在的建筑物,然后他们属于哪个部门。
根据人员所在的部门,可以添加不同的组。我想让它只执行一次,直到他们关闭并重新打开应用程序,有点像白名单。
问题在于,当想要使用泛型方法时,枚举似乎是一个巨大的痛苦。
我能够找到一种方法来做到这一点,使用通用静态字典,但它看起来很糟糕,我不知道是否有我忽略的东西或者更简单的方法来做我想要的。
private async Task CheckWhiteList(PowerShell power, KeyValuePair<string, Enum> history)
{
switch ((Building)Model.BuildingSelectedIndex)
{
case Building.CaneRidge:
history = new KeyValuePair<string, Enum>(Model.UserID, (CaneRidgeSettings.Departments)Model.DepartmentSelectedIndex);
if (!WhiteList.Contains(history))
{
WhiteList.Add(history.Key, history.Value);
await power.InvokeAsync();
}
break;
case Building.Carothers:
history = new KeyValuePair<string, Enum>(Model.UserID, (CarothersSettings.Departments)Model.DepartmentSelectedIndex);
if (!WhiteList.Contains(history))
{
WhiteList.Add(history.Key, history.Value);
await power.InvokeAsync();
}
break;
case Building.CSC:
history = new KeyValuePair<string, Enum>(Model.UserID, (CSCSettings.Departments)Model.DepartmentSelectedIndex);
if (!WhiteList.Contains(history))
{
WhiteList.Add(history.Key, history.Value);
await power.InvokeAsync();
}
break;
case Building.HQ:
history = new KeyValuePair<string, Enum>(Model.UserID, (HQSettings.Departments)Model.DepartmentSelectedIndex);
if (!WhiteList.Contains(history))
{
WhiteList.Add(history.Key, history.Value);
await power.InvokeAsync();
}
break;
default:
break;
}
请注意,关键是他们的用户 ID,我不想将用户可能选择错误部门或错误建筑物的情况列入白名单。这就是为什么它必须匹配两个值。
【问题讨论】:
-
能否请您出示您的“通用静态字典”代码?我正要建议这种事情作为解决方案,但想先看看你是如何做到的。
-
public static Dictionary
WhiteList = new Dictionary ();所有的 Dictionary 就是,只使用 TValue 的基本 Enum 类 -
那为什么看起来很糟糕?
-
因为完成这项工作的唯一方法是把它放在一个 switch 语句中,如上所示,有很多重复的代码。我不确定是否有更好的方法来处理这种情况。
-
我已经发布了一个没有开关且没有任何重复代码的答案。
标签: c# dictionary generics enums