我可以在C#中为枚举创建接口吗 [英] Can I create interface for enums in C#

查看:87
本文介绍了我可以在C#中为枚举创建接口吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个枚举,如下所示:

Suppose I have two enums as follow:

namespace A
{
    public enum AE
    {
        AE_0,
        AE_1
    }
}

namespace B
{
    public enum BE
    {
        BE_0,
        BE_1
    }
}

我想使用这两个枚举看起来像一个枚举,以便在一个函数中,我们可以同时使用F(AE)和F(BE),而无需定义两个函数。

I would like to use these two enums looks like one so that, in a function, we can use both F(AE) and F(BE) without defining two functions.

据我所知,我们可以为两个不同的类创建一个接口,以便如果我们将接口分配为参数,则可以使用这两个类。

As far as I know, we can create an interface for two different classes so that if we assign the interface as a parameter, these two classes can be used.

我可以为枚举做同样的事情吗?

Can I do the same for enum?

谢谢。

编辑:我提出了这个问题,因为我已经在名称空间A中拥有枚举A。现在我想在名称空间B中添加枚举B,而又不涉及名称空间A中的任何内容。命名空间A,我已经有一个以枚举A作为参数的函数F。现在,我想将函数F与命名空间B中的枚举B一起使用。由于出现了枚举A和枚举B无法相互转换的错误,因此出现了错误。谢谢。

Edit: I raise the problem because I already have enum A in namespace A. Now I would like to add enum B in namespace B without touching anything in namespace A. However, in namespace A, I already have a function F with enum A as parameter. Now I would like to use function F with enum B in namespace B. I got an error because enum A and enum B cannot convert to each other. Thank you.

推荐答案

不,您不能,因为枚举会继承来自 System.Enum 仅此而已。

No, you cannot, because an enum inherits from System.Enum and nothing more.

另外,尽管看起来很明显,但对枚举应用接口将不会产生期望的结果,因为枚举成员被实现为 static 值,并且接口无法指定静态值。

Additionally, despite obvious appearances, applying an interface to an enum would not yield the desired results, since the enum members are implemented as static values, and an interface cannot specify static values.

最后,如果您确实有一些东西应该接受两种枚举参数,请考虑使用两个单独的 enum 还是单个 enum [标志]

Finally, if you have something that really should accept two kinds of enum parameters, consider whether they should be two separate enums, or a single enum with [Flags].

这篇关于我可以在C#中为枚举创建接口吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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