解决方法缺乏一个枚举的通用约束解决方法

2023-09-02 10:15:38 作者:跌進你夢里

我想要做的是这样的:我有枚举与结合标记值

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

不幸的是C#的泛型约束的地方都没有枚举的限制,只有类和结构。 C#不看枚举的结构(即使它们是值类型),所以我不能添加扩展类型是这样的。

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?

推荐答案

编辑:这是现在住在UnconstrainedMelody的0.0.0.2版本

(按照要求在我的博客帖子大约枚举约束的。我已经包含下面为求一个独立的答案基本事实。)

(As requested on my blog post about enum constraints. I've included the basic facts below for the sake of a standalone answer.)

最好的解决办法是,等我把它列入 UnconstrainedMelody 1 。这是一个库,它采用C#code与假的约束,如

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

和把它变成

where T : struct, System.Enum

通过postbuild一步。

via a postbuild step.

这应该不会太难写使用isset ...虽然餐饮为的Int64 基于和 UINT64 为基础的标志可能是棘手的问题。 (我闻到了一些辅助的方法来了,基本上让我枚举对待任何标志,如果它有一个基本类型 UINT64

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.

编辑:我不知道关于使用isset 作为名字,顺便说一句。选项​​:

I'm not sure about IsSet as a name, by the way. Options:

包含 包含 HasFlag(或HasFlags) 在使用isset(它肯定是一个选项)

思想的欢迎。我敢肯定,这将是一段时间之前,任何在石头被设置反正...

Thoughts welcome. I'm sure it'll be a while before anything's set in stone anyway...

1 或提交的补丁,当然...

1 or submit it as a patch, of course...