c# - 针对多个接口(interface)编程

标签 c# oop

我非常喜欢这个提示:“针对接口(interface)而不是实现进行编程”,并且我正在努力始终如一地遵循它。然而,当我必须将我的代码与必须从多个接口(interface)继承的对象分离时,我不确定如何保持这个原则的工作。一个典型的例子可能是:

namespace ProgramAgainstInterfaces
{
    interface IMean
    {
            void foo();
    }  

    class Meaning : IMean , IDisposable
    {
        public void Dispose()
        {
            Console .WriteLine("Disposing..." );
        }

        public void foo()
        {
            Console .WriteLine("Doing something..." );           
        }
    }

   class DoingSomething
   {
        static void Main( string[] args)
        {
            IMean ThisMeaning = (IMean ) new Meaning ();  // Here the issue: I am losing the IDisposable methods
            ThisMeaning.foo();
            ThisMeaning.Dispose();                     // Error: i cannot call this method losing functionality
        }
   }   
}

解决这个问题的一种可能方法是定义一个从两个接口(interface)继承的临时接口(interface):

namespace ProgramAgainstInterfaces
{
    interface IMean
    {
            void foo();
    }

    interface ITry : IMean , IDisposable
    {
    }

    class Meaning : ITry
    {
        public void Dispose()
        {
            Console .WriteLine("Disposing..." );
        }

        public void foo()
        {
            Console .WriteLine("Doing something..." );           
        }
    }

   class DoingSomething
   {
        static void Main( string[] args)
        {
            ITry ThisMeaning = (ITry ) new Meaning ();  // This works
            ThisMeaning.foo();
            ThisMeaning.Dispose();   // The method is available
        }
   }   
}

但我不确定这是否是更紧凑和有效的解决方案:我可以有更复杂的多重继承层次结构,这增加了复杂性,因为我必须创建仅用作容器的接口(interface)。有更好的设计方案吗?

最佳答案

如果作为一个“IMean”对象涉及到总是一次性的,那么你应该让接口(interface)像这样实现它:

public interface IMean : IDisposable
{
    ...
}

但是,如果让一个对象实现 IMean 而不是一次性的有意义,那么我认为您建议的解决方案是最好的:创建一个中间接口(interface),这样您就可以拥有:

public interface IMean
{
    ...
}

public interface IDisposableMean : IMean, IDisposable
{
    ...
}

关于c# - 针对多个接口(interface)编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16166165/

相关文章:

c# - 通过 datacontract 使用 WCF Restful 服务

c# - 为什么我的 C# 默认接口(interface)实现在具体类定义中没有被识别?

java - 在参数之前和之后分配实例变量有什么区别?

c# - 服务器如何知道这是浏览器请求还是 api 请求?

javascript - Internet Explorer 弹出消息在 Windows 10 中被 chop

php - 在 zend 中在哪里保存自定义自动加载器?

php - 如何在 Laravel 5 中的类之间共享作用域

java - 从工厂中的字符串参数获取正确的对象

c# - 如何检测彼此靠近的两个窗口

c# - 使用 BackgroundWorker 时出现异常