任何人都知道一个很好的解决方法,因为缺少枚举泛型约束? [英] Anyone know a good workaround for the lack of an enum generic constraint?
问题描述
我想做的是这样的:我有枚举的组合标记值。
public static class EnumExtension
{
public static bool IsSet< T>(此T输入,T matchTo)
其中T:枚举//我想要的限制在C#3中不存在
{
return(input& matchTo)!= 0;
}
}
那么我可以做:
MyEnum tester = MyEnum.FlagA | MyEnum.FlagB
if(tester.IsSet(MyEnum.FlagA))
// act on flag a
不幸的是C#的泛型,其中约束没有枚举限制,只有类和结构体。 C#没有将枚举看作结构体(即使它们是值类型),所以我无法添加这样的扩展类型。
任何人都知道解决方法? >
编辑:现在现在是UnconstrainedMelody的0.0.0.2版本。
(根据我的关于枚举约束的博客文章为了独立的答案,我已经包括了下面的基本事实。)
最好的解决方案是等待我将其包含在无约束的旋律 1 中。这是一个使用C#代码与假约束如C / / code>
并将其转换为
其中T:struct,System.Enum
通过postbuild步骤。
不应太难写 IsSet
...虽然适合 Int64
- 和 UInt64
的标志可能是棘手的一部分。 (我闻到一些帮助方法,基本上允许我处理任何标志枚举,就好像它有一个基本类型的 UInt64
。)
如果您调用
tester.IsSet(MyFlags.A | MyFlags .C)
?应该检查所有是否设置了指定的标志?这将是我的期望。
我会在今天晚上回家的路上尝试这样做...我希望有一个有用的枚举方法快速闪电让图书馆快速获得可用的标准,然后放松一点。
编辑:我不确定 IsSet
作为一个名字,顺便说一句。选项:
- 包含
- 包含
- HasFlag或HasFlags)
- IsSet(当然是一个选项)
我确定这将是一段时间之前任何东西设置在石头...
1 或将其作为补丁提交,当然...
What I want to do is something like this: I have enums with combined flagged values.
public static class EnumExtension
{
public static bool IsSet<T>( this T input, T matchTo )
where T:enum //the constraint I want that doesn't exist in C#3
{
return (input & matchTo) != 0;
}
}
So then I could do:
MyEnum tester = MyEnum.FlagA | MyEnum.FlagB
if( tester.IsSet( MyEnum.FlagA ) )
//act on flag a
Unfortunately C#'s generic where constraints have no enum restriction, only class and struct. C# doesn't see enums as structs (even though they are value types) so I can't add extension types like this.
Anyone know a workaround?
EDIT: This is now live in version 0.0.0.2 of UnconstrainedMelody.
(As requested on my blog post about enum constraints. I've included the basic facts below for the sake of a standalone answer.)
The best solution is to wait for me to include it in UnconstrainedMelody1. This is a library which takes C# code with "fake" constraints such as
where T : struct, IEnumConstraint
and turns it into
where T : struct, System.Enum
via a postbuild step.
It shouldn't be too hard to write IsSet
... although catering for both Int64
-based and UInt64
-based flags could be the tricky part. (I smell some helper methods coming on, basically allowing me to treat any flags enum as if it had a base type of UInt64
.)
What would you want the behaviour to be if you called
tester.IsSet(MyFlags.A | MyFlags.C)
? Should it check that all the specified flags are set? That would be my expectation.
I'll try to do this on the way home tonight... I'm hoping to have a quick blitz on useful enum methods to get the library up to a usable standard quickly, then relax a bit.
EDIT: I'm not sure about IsSet
as a name, by the way. Options:
- Includes
- Contains
- HasFlag (or HasFlags)
- IsSet (it's certainly an option)
Thoughts welcome. I'm sure it'll be a while before anything's set in stone anyway...
1 or submit it as a patch, of course...
这篇关于任何人都知道一个很好的解决方法,因为缺少枚举泛型约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!