问题
Ok, so the basis of this post and to explain the title is simple. I have an Interface with a method. That method on the user side will take in an enum as a param. But you can't define enums in an interface therefore I don't see how I can even define this method then if I'm expecting a type Enum as one of the incoming params.
So how do you handle this situation? How can you still get that method in your Interface. You don't know what Enum they'll require to be sent in but you know for sure you want it to be an enum instead of magic strings.
An Enum is not a reference type so you can't use Object as the type for the incoming param. So not sure what to do here.
回答1:
interface MyInterface
{
void MyMethod(Enum @enum);
}
回答2:
public enum MyEnum
{
Hurr,
Durr
}
public interface MyInterface
{
void MyMethod(MyEnum value);
}
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.
回答3:
Another solution could be to use Generic types:
public enum MyEnum
{
Foo,
Bar
}
public interface IDummy<EnumType>
{
void OneMethod(EnumType enumVar);
}
public class Dummy : IDummy<MyEnum>
{
public void OneMethod(MyEnum enumVar)
{
// Your code
}
}
Also, since C# 7.3, you can add a generic constraint to accept only Enum types:
public interface IDummy<EnumType> where EnumType : Enum
{
void OneMethod(EnumType enumVar);
}
回答4:
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.
回答5:
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.
来源:https://stackoverflow.com/questions/3216340/how-to-represent-an-enum-in-an-interface-when-you-cant