相关疑难解决方法(0)

任何人都知道缺乏枚举通用约束的好方法吗?

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

那么我可以这样做:

MyEnum tester = MyEnum.FlagA | MyEnum.FlagB

if( tester.IsSet( MyEnum.FlagA ) )
    //act on flag a
Run Code Online (Sandbox Code Playgroud)

不幸的是,C#的通用,其中约束没有枚举限制,只有类和结构.C#不会将枚举视为结构(即使它们是值类型),因此我无法像这样添加扩展类型.

有没有人知道解决方法?

.net c# enums flags

87
推荐指数
6
解决办法
2万
查看次数

标签 统计

.net ×1

c# ×1

enums ×1

flags ×1