我非常喜欢这个建议:“针对接口编程,而不是实现”,并且我正在努力始终遵循它。但是当我必须将代码与必须从多个接口继承的对象解耦时,我不确定如何让这个原则继续发挥作用。一个典型的例子可能是:
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
}
}
}
解决这个问题的一个可能方法是定义一个临时接口,该接口继承自这两个接口:
一个可能的解决方案是定义一个特定的接口,该接口同时继承这两个接口:
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
}
}
}
但我不确定这是否是更紧凑和有效的解决方案:我可能会有更复杂的多重继承层次结构,并且这会增加复杂性,因为我必须创建仅充当容器的接口。是否有更好的设计解决方案?
var disposable = ThisMeaning as IDisposable; if(disposable != null) disposable.Dispose()
- 这意味着您在运行时发现实现,而不必在编译时知道它们。 - Charlehdef doSomething(m: IMean with IDisposable) {}
- artem