任何人都知道缺乏一个枚举泛型约束的一个很好的解决方法吗? [英] Anyone know a good workaround for the lack of an enum generic constraint?

查看:166
本文介绍了任何人都知道缺乏一个枚举泛型约束的一个很好的解决方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 <包括它/ SUP>。这是采用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...

这篇关于任何人都知道缺乏一个枚举泛型约束的一个很好的解决方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆