我非常喜欢这个提示:“针对接口(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/