如何打开一个设置了flags属性的枚举(或更精确地用于位操作)?
我希望能够在一个匹配声明值的开关中击中所有情况。
问题是,如果我有以下枚举
[Flags()]public enum CheckType
{
Form = 1,
QueryString = 2,
TempData = 4,
}
我想使用像这样的开关
switch(theCheckType)
{
case CheckType.Form:
DoSomething(/*Some type of collection is passed */);
break;
case CheckType.QueryString:
DoSomethingElse(/*Some other type of collection is passed */);
break;
case CheckType.TempData
DoWhatever(/*Some different type of collection is passed */);
break;
}
如果“theCheckType”设置为CheckType.Form | CheckType.TempData我希望它能同时击中两个案例。显然,由于中断,它不会在我的示例中同时出现,但除此之外它也会失败,因为CheckType.Form不等于CheckType.Form | CheckType.TempData
然后我能看到的唯一解决方案就是为每个可能的枚举值组合提供一个案例?
像
这样的东西 case CheckType.Form | CheckType.TempData:
DoSomething(/*Some type of collection is passed */);
DoWhatever(/*Some different type of collection is passed */);
break;
case CheckType.Form | CheckType.TempData | CheckType.QueryString:
DoSomething(/*Some type of collection is passed */);
DoSomethingElse(/*Some other type of collection is passed */);
break;
... and so on...
但这真的不是很理想(因为它会很快变大)
现在,我有3个If条件,而不是
像
这样的东西if ((_CheckType & CheckType.Form) != 0)
{
DoSomething(/*Some type of collection is passed */);
}
if ((_CheckType & CheckType.TempData) != 0)
{
DoWhatever(/*Some type of collection is passed */);
}
....
但这也意味着如果我有一个包含20个值的枚举,则必须每次都通过20个If条件,而不是像使用开关那样“跳转”到所需的“case”/。
有没有解决这个问题的神奇解决方案?
我已经考虑过循环声明的值然后使用开关的可能性,然后它只会触发声明的每个值的开关,但我不知道它将如何工作,如果它的性能副是一个好主意(与很多if相比)?
是否有一种简单的方法可以遍历声明的所有枚举值?
我只能使用ToString()并按“,”拆分,然后遍历数组并解析每个字符串。
更新:
我发现我的工作做得还不够好。 我的例子很简单(试图简化我的场景)。
我将它用于Asp.net MVC中的ActionMethodSelectorAttribute,以确定解析url / route时方法是否可用。
我是通过在方法
上声明类似的东西来实现的[ActionSelectorKeyCondition(CheckType.Form | CheckType.TempData, "SomeKey")]
public ActionResult Index()
{
return View();
}
这意味着它应检查Form或TempData是否具有为可用方法指定的密钥。
它将调用的方法(doSomething(),doSomethingElse()和doWhatever()在我之前的例子中)实际上将bool作为返回值,并将使用参数调用(不共享接口的不同集合)可以使用 - 请参阅下面链接中的示例代码等。)
为了更好地了解我在做什么,我已经粘贴了一个关于我在pastebin上实际做什么的简单示例 - 可以在http://pastebin.com/m478cc2b8
找到答案 0 :(得分:43)
这个怎么样?当然,DoSomething等的参数和返回类型可以是你喜欢的任何东西。
class Program
{
[Flags]
public enum CheckType
{
Form = 1,
QueryString = 2,
TempData = 4,
}
private static bool DoSomething(IEnumerable cln)
{
Console.WriteLine("DoSomething");
return true;
}
private static bool DoSomethingElse(IEnumerable cln)
{
Console.WriteLine("DoSomethingElse");
return true;
}
private static bool DoWhatever(IEnumerable cln)
{
Console.WriteLine("DoWhatever");
return true;
}
static void Main(string[] args)
{
var theCheckType = CheckType.QueryString | CheckType.TempData;
var checkTypeValues = Enum.GetValues(typeof(CheckType));
foreach (CheckType value in checkTypeValues)
{
if ((theCheckType & value) == value)
{
switch (value)
{
case CheckType.Form:
DoSomething(null);
break;
case CheckType.QueryString:
DoSomethingElse(null);
break;
case CheckType.TempData:
DoWhatever(null);
break;
}
}
}
}
}
答案 1 :(得分:13)
标志枚举可以视为一种简单的整数类型,其中每个单独的位对应一个标记值。您可以利用此属性将带位标记的枚举值转换为布尔数组,然后从相关的委托数组中调度您关心的方法。
编辑: 通过使用LINQ和一些辅助函数,我们当然可以使这段代码更紧凑,但我认为用不太复杂的形式更容易理解。这可能是可维护性胜过优雅的情况。
以下是一个例子:
[Flags()]public enum CheckType
{
Form = 1,
QueryString = 2,
TempData = 4,
}
void PerformActions( CheckType c )
{
// array of bits set in the parameter {c}
bool[] actionMask = { false, false, false };
// array of delegates to the corresponding actions we can invoke...
Action availableActions = { DoSomething, DoSomethingElse, DoAnotherThing };
// disassemble the flags into a array of booleans
for( int i = 0; i < actionMask.Length; i++ )
actionMask[i] = (c & (1 << i)) != 0;
// for each set flag, dispatch the corresponding action method
for( int actionIndex = 0; actionIndex < actionMask.Length; actionIndex++ )
{
if( actionMask[actionIndex])
availableActions[actionIndex](); // invoke the corresponding action
}
}
或者,如果您评估的顺序无关紧要,这里更简单,更清晰的解决方案也可以。如果顺序很重要,请将位移操作替换为包含要按其评估顺序的标记的数组:
int flagMask = 1 << 31; // start with high-order bit...
while( flagMask != 0 ) // loop terminates once all flags have been compared
{
// switch on only a single bit...
switch( theCheckType & flagMask )
{
case CheckType.Form:
DoSomething(/*Some type of collection is passed */);
break;
case CheckType.QueryString:
DoSomethingElse(/*Some other type of collection is passed */);
break;
case CheckType.TempData
DoWhatever(/*Some different type of collection is passed */);
break;
}
flagMask >>= 1; // bit-shift the flag value one bit to the right
}
答案 2 :(得分:6)
只需使用HasFlag
即可if(theCheckType.HasFlag(CheckType.Form)) DoSomething(...);
if(theCheckType.HasFlag(CheckType.QueryString)) DoSomethingElse(...);
if(theCheckType.HasFlag(CheckType.TempData)) DoWhatever(...);
答案 3 :(得分:4)
您将填写的Dictionary<CheckType,Action>
如何
dict.Add(CheckType.Form, DoSomething);
dict.Add(CheckType.TempDate, DoSomethingElse);
...
你的价值分解
flags = Enum.GetValues(typeof(CheckType)).Where(e => (value & (CheckType)e) == (CheckType)e).Cast<CheckType>();
然后
foreach (var flag in flags)
{
if (dict.ContainsKey(flag)) dict[flag]();
}
(代码未经测试)
答案 4 :(得分:3)
使用C#7,您现在可以编写如下内容:
public void Run(CheckType checkType)
{
switch (checkType)
{
case var type when CheckType.Form == (type & CheckType.Form):
DoSomething(/*Some type of collection is passed */);
break;
case var type when CheckType.QueryString == (type & CheckType.QueryString):
DoSomethingElse(/*Some other type of collection is passed */);
break;
case var type when CheckType.TempData == (type & CheckType.TempData):
DoWhatever(/*Some different type of collection is passed */);
break;
}
}
答案 5 :(得分:1)
根据您的编辑和现实代码,我可能会更新IsValidForRequest
方法,看起来像这样:
public sealed override bool IsValidForRequest
(ControllerContext cc, MethodInfo mi)
{
_ControllerContext = cc;
var map = new Dictionary<CheckType, Func<bool>>
{
{ CheckType.Form, () => CheckForm(cc.HttpContext.Request.Form) },
{ CheckType.Parameter,
() => CheckParameter(cc.HttpContext.Request.Params) },
{ CheckType.TempData, () => CheckTempData(cc.Controller.TempData) },
{ CheckType.RouteData, () => CheckRouteData(cc.RouteData.Values) }
};
foreach (var item in map)
{
if ((item.Key & _CheckType) == item.Key)
{
if (item.Value())
{
return true;
}
}
}
return false;
}
答案 6 :(得分:0)
在C#7中应该是可能的
switch (t1)
{
case var t when t.HasFlag(TST.M1):
{
break;
}
case var t when t.HasFlag(TST.M2):
{
break;
}
答案 7 :(得分:0)
将其保留为基本类型,这很妙,它可以告诉您何时存在重复值。
[Flags]
public enum BuildingBlocks_Property_Reflection_Filters
{
None=0,
Default=2,
BackingField=4,
StringAssignment=8,
Base=16,
External=32,
List=64,
Local=128,
}
switch ((int)incomingFilter)
{
case (int)PropFilter.Default:
break;
case (int)PropFilter.BackingField:
break;
case (int)PropFilter.StringAssignment:
break;
case (int)PropFilter.Base:
break;
case (int)PropFilter.External:
break;
case (int)PropFilter.List:
break;
case (int)PropFilter.Local:
break;
case (int)(PropFilter.Local | PropFilter.Default):
break;
}
答案 8 :(得分:-1)
最简单的方法是执行ORed
枚举,在您的情况下,您可以执行以下操作:
[Flags()]public enum CheckType
{
Form = 1,
QueryString = 2,
TempData = 4,
FormQueryString = Form | QueryString,
QueryStringTempData = QueryString | TempData,
All = FormQueryString | TempData
}
完成enum
设置后,现在可以轻松执行switch
声明。
例如,如果我已设置以下内容:
var chkType = CheckType.Form | CheckType.QueryString;
我可以使用以下switch
语句,如下所示:
switch(chkType){
case CheckType.Form:
// Have Form
break;
case CheckType.QueryString:
// Have QueryString
break;
case CheckType.TempData:
// Have TempData
break;
case CheckType.FormQueryString:
// Have both Form and QueryString
break;
case CheckType.QueryStringTempData:
// Have both QueryString and TempData
break;
case CheckType.All:
// All bit options are set
break;
}
更清洁,您不需要在if
使用HasFlag
声明。您可以进行任何所需的组合,然后使switch语句易于阅读。
我建议您将enums
分开,试试看你是不是将不同的东西混合到同一个enum
中。您可以设置多个enums
以减少案例数。