如何在遵守接口的 class 中定义枚举

How to define enums in a class abiding by an interface

界面为:

public interface CommonPluginInterface
{
    string GetPluginName();
    string GetPluginType();
    bool ElaborateReport();
}

现在我希望所有派生的 classes 通过字符串和枚举来标识自己。对于字符串来说很容易,因为它是硬编码的:

public class PluginReport_Excel : MarshalByRefObject, CommonPluginInterface
{
    public string GetPluginName()
    {
        return "Foo";
    }
}

但另外我还希望它通过枚举来识别。所以我想把接口放进去,但是接口不能包含成员。

所以我想

public class CommonPluginClass
{
    private enum ePluginType { UNKNOWN, EXCEL, EXCEL_SM, RTF}
    private ePluginType pluginType;
}

并使派生的 class 也从中派生,但这是不可能的,因为它说:

Class 'PluginReport_Excel' cannot have multiple base classes: 'MarshalByRefObject' and 'CommonPluginClass'

我需要 MarshalByRefObject。 感谢您的帮助。

您可以在具有枚举类型的界面上使用 属性:

public interface CommonPluginInterface
{
    string GetPluginName();
    bool ElaborateReport();
    ePluginType PluginType { get; }
}

现在所有实施 类 也必须相应地设置 属性。但是,您会将枚举设置为 public.

public class PluginReport_Excel : MarshalByRefObject, CommonPluginInterface
{
    public string GetPluginName()
    {
        return "Foo";
    }
    public PluginType { get { return ePluginType.Excel; } }
}

或者,当您想使用 GetPluginType 方法时,您可以简单地将枚举值转换为字符串:

public class PluginReport_Excel : MarshalByRefObject, CommonPluginInterface
{
    public string GetPluginName()
    {
        return "Foo";
    }
    public string GetPluginType()
    {
        return this.PluginType.ToString();
    }
    public PluginType { get { return ePluginType.Excel; } }
}

创建一个 MarshalByRefCommonPluginClass 怎么样?

public class MarshalByRefCommonPluginClass : MarshalByRefObject
{
    private enum ePluginType { UNKNOWN, EXCEL, EXCEL_SM, RTF}
    private ePluginType pluginType;
}

顺便说一句,naming conventions 通常意味着接口有一个 'I' 前缀(ICommonPlugin),类型将使用大写字母(EPluginType)。

单独定义一个枚举并将其定义为 GetPluginType 方法的 return 类型。

public enum ePluginType 
{ 
    UNKNOWN, 
    EXCEL, 
    EXCEL_SM, 
    RTF
} 

public interface CommonPluginInterface
{
    string GetPluginName();
    ePluginType GetPluginType();
    bool ElaborateReport();
}

public class PluginReport_Excel : MarshalByRefObject, CommonPluginInterface
{
    public ePluginType GetPluginType()
    {
        return ePluginType.EXCEL;
    }

    //implement other interface members
}