【问题标题】:How to define enums in a class abiding by an interface如何在遵循接口的类中定义枚举
【发布时间】:2016-11-22 01:04:36
【问题描述】:

界面是:

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

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

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

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

“PluginReport_Excel”类不能有多个基类:“MarshalByRefObject”和“CommonPluginClass”

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

【问题讨论】:

标签: c# inheritance interface derived-class


【解决方案1】:

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

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
}

【讨论】:

    【解决方案2】:

    您可以在接口上使用枚举类型的属性:

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

    现在所有实现类也必须相应地设置属性。但是,您需要将枚举公开。

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

    【讨论】:

      【解决方案3】:

      创建一个MarshalByRefCommonPluginClass 怎么样?

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

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

      【讨论】:

        猜你喜欢
        • 2011-01-31
        • 1970-01-01
        • 2019-10-01
        • 2021-01-24
        • 1970-01-01
        • 2016-09-08
        • 1970-01-01
        • 2011-09-02
        • 1970-01-01
        相关资源
        最近更新 更多