任何人都知道缺少枚举通用约束的好方法吗? [英] Anyone know a good workaround for the lack of an enum generic constraint?

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

问题描述

我想做的是这样的事情:我有带有组合标记值的枚举.

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;
    }
}

那么我可以这样做:

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.

有人知道解决方法吗?

推荐答案

现在在 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.)

最好的解决办法是等我把它包含在UnconstrainedMelody1.这是一个库,它采用带有假"约束的 C# 代码,例如

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

通过构建后步骤.

编写 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)

?它是否应该检查 all 指定的标志是否已设置?那将是我的期望.

? 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天全站免登陆