< T>其中T:Enum“不工作 [英] "Class of <T> where T : Enum" not working

查看:206
本文介绍了< T>其中T:Enum“不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

创建泛型方法约束T到枚举

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

Is there any reason why we can't do this in C#? And, if possible, how can I do something similar!

我想要的:


    public class<T> ATag where T : enum {
        [Some code ..]
    }

    public class<T> classBase where T : enum {
        public IDictionnary tags { get; set; }
    }

因此,当调用它的时候,我只得到我的一个枚举

So, when it comes the time to call it, I'm sur to get only one of my enum values.



    public class AClassUsingTag : classBase<PossibleTags> {
        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'

谢谢!

推荐答案

你不能这样做,因为规范说你不能,基本上。这是恼人,但这是它的方式。 CLR支持它没有问题。我的猜测 是当第一次设计泛型时,CLR可能不支持它,所以它也被禁止在语言中...和C#团队didn不会得到关于它的备注,然后被支持,或者太晚了包括它。代表同样恼人。

You can't do it because the spec says you can't, basically. It's annoying, but that's the way it is. The CLR supports it with no problem. My guess is that when generics were first being designed, the CLR might not have supported it, so it was prohibited in the language too... and either the C# team didn't get the memo about it then being supported, or it was too late too include it. Delegates are similarly annoying.

有一个解决方法...看看我的 Unconstrained Melody 项目。你可以自己使用相同的方法。我同时撰写了博文,详细信息。

As for a workaround... have a look at my Unconstrained Melody project. You could use the same approach yourself. I wrote a blog post at the same time, which goes into more details.

这篇关于&lt; T&gt;其中T:Enum“不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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