我正在研究复合应用程序指南,并经常遇到类型接口对象的实例化,例如:
IShell shell = new Shell();
而不是类型:
Shell shell = new Shell();
答案 0 :(得分:2)
如果类具有接口方法的显式实现,您可能希望这样做。考虑这个例子:
public interface ISomething { void Action(); }
public interface ISomethingElse {void Action(); }
public class Something : ISomething
{
public void Action()
{
}
void ISomething.Action()
{
}
}
public class Something2 : ISomething, ISomethingElse
{
void ISomething.Action()
{
}
void ISomethingElse.Action()
{
}
}
如果你想在Something上调用ISomething.Action,那么你必须通过ISomething变量来调用它。即使在Something2中,如果不通过界面执行,也会隐藏Action方法。
那就是说,你通常希望避免这样的实现。我怀疑一个框架类会强迫你进入那个,但那将是通过接口声明它的场景。
更新1:要稍微澄清一下,有关如何获取方法的一些额外代码:
Something some = new Something();
some.Action(); //calls the regular Action
ISomething isome = some;
isome.Action(); //calls the ISomething.Action
((ISomething)some).Action(); //again, calls ISomething.Action
Something2 some2 = new Something2();
some2.Action();//compile error
((ISomething)some2).Action(); //calls ISomething.Action
((IsomethingElse)some2).Action(); // calls ISomethingElse.Action
答案 1 :(得分:1)
明显不同的是,第一个允许你只使用shell作为IShell,第二个允许你使用Shell的所有功能,恰好也包括IShell的功能。
也许你可以把观点从维护者那里拿走。
第一个是说我们需要的是支持IShell的东西的实例,如果我们愿意,我们可以将它改为其他对象。
第二个是说我们必须为它提供的某些功能专门设置一个Shell对象。
答案 2 :(得分:1)
使用第一个示例,您只能在源代码中使用IShell中指定的功能,在第二个示例中,您还可以使用未在界面中定义的Shell对象的其他功能。
如果您需要将Shell对象替换为具有相同功能但具有不同实现的其他对象ShellEx,则第一种解决方案提供了更大的灵活性。为此,您只需要更改
IShell shell = new Shell();
到
IShell shell = new ShellEx();
不需要更改其余代码。
第二种解决方案使您可以使用Shell对象的完整功能。
您必须根据具体情况决定哪种解决方案在当前情况下是可取的。