开发者

How to represent an Enum in an Interface?

开发者 https://www.devze.com 2023-01-06 11:36 出处:网络
How could I define an Interface which h开发者_运维问答as a method that has Enum as a paramater when enums cannot be defined in an interface?

How could I define an Interface which h开发者_运维问答as 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?


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.


interface MyInterface
{
    void MyMethod(Enum @enum);
}


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);
}


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.


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:

public interface IConfigProvider
{
    enum OUType
    {
        Prop1,
        Prop2
    };


    string GetConfig(OUType outType);
}

public class ConfigProvider
{
    enum OUType
    {
       Prop1,
       Prop2
    };
    
    public string GetConfig(IConfigProvider.OUType outType)
    {
        ...
    }
    
}

Usage:

configProvider.GetConfig(IConfigProvider.OUType.Prop1)
0

精彩评论

暂无评论...
验证码 换一张
取 消