如何在接口中表示枚举?
当无法在接口中定义枚举时,如何定义一个具有以 Enum
作为参数的方法的接口?
由于 Enum
不是引用类型,因此 Object
类型不能用作传入参数的类型,那么怎么办呢?
How could I define an Interface which has a method that has Enum
as a paramater when enums cannot be defined in an interface?
For an Enum
is not a reference type so an Object
type cannot be used as the type for the incoming param, so how then?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果这不是您正在谈论的事情,请发表评论,以便人们可以了解您的问题是什么。因为,虽然枚举没有在接口中定义,但这是一个完全正常且可接受的设计。
If this isn't what you're talking about doing, leave a comment so people can understand what your issue is. Because, while the enum isn't defined within the interface, this is a completely normal and acceptable design.
另一个解决方案可能是使用泛型类型:
此外,从 C# 7.3 开始,您可以添加泛型约束以仅接受 Enum 类型:
Another solution could be to use Generic types:
Also, since C# 7.3, you can add a generic constraint to accept only Enum types:
定义枚举就像定义类或定义接口一样。您可以将它放在一个类文件中,在命名空间内但在类定义之外,但是如果有多个类使用它,您将它放入哪一个,无论您选择哪一个,您都会得到“类型名称与文件不匹配”名”警告。因此,“正确”的方法是将其放入自己的文件中,就像类或接口一样:
MyEnum.cs
namespace MyNamespace
{
内部枚举 MyEnum { Value1, Value2, Value3, Value4, Value5 };
}
然后命名空间内的任何接口或类都可以访问它。
Defining an enum is like defining a class or defining an interface. You could just put it in one of your class files, inside the namespace but outside the class definition, but if several classes use it, which one do you put it in, and whichever you choose you will get "Type name does not match file name" warnings. So the "right" way to do it is to put it in its own file, as you would a class or an interface:
MyEnum.cs
namespace MyNamespace
{
internal enum MyEnum { Value1, Value2, Value3, Value4, Value5 };
}
Then any interfaces or classes within the namespace can access it.
如果您谈论的是泛型接口,并且 C# 不允许您将泛型类型限制为枚举,则 此问题的答案包括两种不同的解决方法。
If you're talking about generic interfaces and the fact that C# doesn't let you constrain generic types to be enums, the answers to this question include two different work-arounds.
您必须在两侧实现枚举并引用接口命名空间,例如:
用法:
You must implement the enum in both side and refer the Interface namespace, eg:
Usage: