"Class of where T : Enum" 不起作用。

18 浏览
0 Comments

"Class of where T : Enum" 不起作用。

这个问题在这里已经有答案了:

可能是重复的问题:

创建T被限制为枚举类型的通用方法

在C#中有什么原因不能这样做吗?如果可能,我该怎么做类似的事情!

我想要的:

public class ATag where T : enum {
    [Some code ..]
}
public class classBase where T : enum {
    public IDictionary<T, string> tags { get; set; }
}

所以,在调用它的时候,我确定只会得到我的一个枚举值。

public class AClassUsingTag : classBase {
    public void AMethod(){
         this.tags.Add(PossibleTags.Tag1, "Hello World!");
         this.tags.Add(PossibleTags.Tag2, "Hello Android!");
    }
}
public enum PossibleTags {
    Tag1, Tag2, Tag3
}

错误信息:“约束不能是特殊类\'System.Enum\'”

谢谢!

admin 更改状态以发布 2023年5月21日
0
0 Comments

这是不可能的。但是如果你对运行时检查感兴趣,可以这样做:

class A
        {
            static A()
            {
                if(!typeof(T).IsEnum)
                {
                    throw new Exception();
                }
            }
        }

0
0 Comments

基本上,规范规定了你不能这么做。这很烦人,但这就是事实。CLR 支持它没问题。我猜想当泛型首次设计时,CLR 可能不支持它,所以在语言中被禁止使用.... 而且 C# 团队可能没有收到有关它是否被支持的备忘录,或者太晚才包括它。委托也同样令人烦恼。

至于解决方法... 请查看我的Unconstrained Melody项目。您也可以使用相同的方法。同时,我写了一篇博客文章,详细介绍了更多细节。

0