是否可以创建一个通用的按位枚举'IsOptionSet()'方法? [英] Is it possible to create a generic bitwise enumeration 'IsOptionSet()' method?
问题描述
下面的代码可以很容易地传递一个集合的HtmlParserOptions,然后检查一个选项,看看是否被选中。
The below code makes it easy to pass in a set HtmlParserOptions and then check against a single option to see if it's been selected.
[Flags]
public enum HtmlParserOptions
{
NotifyOpeningTags = 1,
NotifyClosingTags = 2,
NotifyText = 4,
NotifyEmptyText = 8
}
private bool IsOptionSet(HtmlParserOptions options, HtmlParserOptions singleOption)
{
return (options & singleOption) == singleOption;
}
我的问题是,是否可以创建此版本的通用版本通过实现方法属性的接口来猜测),它将与具有Flags属性的任何枚举一起使用
My question is, is it possible to create a Generic version of this (I'm guessing through implementing an interface on the method properties) that will work with any enumeration with the Flags attribute?
推荐答案
编辑:
最简单,最好的选择是升级到VS2010 Beta2,并使用.NET 4的 Enum.HasFlag 方法。框架团队为Enum添加了很多不错的补充,使其更好地使用。
The easiest, nicest option is to upgrade to VS2010 Beta2 and use .NET 4's Enum.HasFlag method. The framework team has added a lot of nice additions to Enum to make them nicer to use.
原始(针对当前) NET):
Original (for current .NET):
您可以通过传递枚举而不是泛型:
You can do this by passing Enum, instead of generics:
static class EnumExtensions
{
private static bool IsSignedTypeCode(TypeCode code)
{
switch (code)
{
case TypeCode.Byte:
case TypeCode.UInt16:
case TypeCode.UInt32:
case TypeCode.UInt64:
return false;
default:
return true;
}
}
public static bool IsOptionSet(this Enum value, Enum option)
{
if (IsSignedTypeCode(value.GetTypeCode()))
{
long longVal = Convert.ToInt64(value);
long longOpt = Convert.ToInt64(option);
return (longVal & longOpt) == longOpt;
}
else
{
ulong longVal = Convert.ToUInt64(value);
ulong longOpt = Convert.ToUInt64(option);
return (longVal & longOpt) == longOpt;
}
}
}
:
This works perfectly, like so:
class Program
{
static void Main(string[] args)
{
HtmlParserOptions opt1 = HtmlParserOptions.NotifyText | HtmlParserOptions.NotifyEmptyText;
Console.WriteLine("Text: {0}", opt1.IsOptionSet(HtmlParserOptions.NotifyText));
Console.WriteLine("OpeningTags: {0}", opt1.IsOptionSet(HtmlParserOptions.NotifyOpeningTags));
Console.ReadKey();
}
}
以上打印:
Text: True
OpeningTags: False
尽管如此,它的缺点是不会保护您不要将两种不同类型的枚举类型传递到例程中。你必须合理使用它。
The downside to this, though, is it doesn't protect you from passing two different types of Enum types into the routine. You have to use it reasonably.
这篇关于是否可以创建一个通用的按位枚举'IsOptionSet()'方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!