在c#中隐式和显式实现接口有什么不同?
什么时候用隐式,什么时候用显式?
这两者之间有什么利弊吗?
微软的官方指南(来自第一版框架设计指南)指出,不建议使用显式实现,因为它会给代码带来意想不到的行为。
我认为这个准则在前ioc时代是非常有效的,当你不把东西作为接口传递的时候。
有人能谈谈这方面的问题吗?
在c#中隐式和显式实现接口有什么不同?
什么时候用隐式,什么时候用显式?
这两者之间有什么利弊吗?
微软的官方指南(来自第一版框架设计指南)指出,不建议使用显式实现,因为它会给代码带来意想不到的行为。
我认为这个准则在前ioc时代是非常有效的,当你不把东西作为接口传递的时候。
有人能谈谈这方面的问题吗?
当前回答
显式接口实现的一个重要用途是在需要实现具有混合可见性的接口时。
这个问题和解决方案在c#内部接口这篇文章中有很好的解释。
例如,如果您希望保护应用程序层之间对象的泄漏,该技术允许您指定可能导致泄漏的成员的不同可见性。
其他回答
引用Jeffrey Richter从CLR通过c#编写的 (EIMI的意思是显式接口方法实现)
It is critically important for you to understand some ramifications that exist when using EIMIs. And because of these ramifications, you should try to avoid EIMIs as much as possible. Fortunately, generic interfaces help you avoid EIMIs quite a bit. But there may still be times when you will need to use them (such as implementing two interface methods with the same name and signature). Here are the big problems with EIMIs: There is no documentation explaining how a type specifically implements an EIMI method, and there is no Microsoft Visual Studio IntelliSense support. Value type instances are boxed when cast to an interface. An EIMI cannot be called by a derived type.
如果您使用接口引用,ANY虚链可以在任何派生类上显式地替换为EIMI,并且当这种类型的对象强制转换到接口时,您的虚链将被忽略,并调用显式实现。这根本不是多态性。
EIMIs还可以用于从基本框架接口的实现(如IEnumerable<T>)中隐藏非强类型接口成员,这样你的类就不会直接公开非强类型方法,但在语法上是正确的。
原因# 1
我倾向于使用显式接口实现,当我不鼓励“编程到实现”(来自设计模式的设计原则)。
例如,在一个基于mvp的web应用程序中:
public interface INavigator {
void Redirect(string url);
}
public sealed class StandardNavigator : INavigator {
void INavigator.Redirect(string url) {
Response.Redirect(url);
}
}
现在,另一个类(比如演示者)不太可能依赖于StandardNavigator实现,而更可能依赖于navigator接口(因为实现需要转换为接口才能使用Redirect方法)。
原因# 2
我可能使用显式接口实现的另一个原因是保持类的“默认”接口更简洁。例如,如果我正在开发一个ASP。NET服务器控件,我可能需要两个接口:
类的主接口,供网页开发人员使用;而且 演示者使用的“隐藏”接口,我开发它来处理控件的逻辑
下面是一个简单的例子。这是一个列出客户的组合框控件。在这个例子中,网页开发人员对填充列表不感兴趣;相反,他们只是希望能够通过GUID选择客户或获得所选客户的GUID。演示器将填充第一个页面加载的框,该演示器由控件封装。
public sealed class CustomerComboBox : ComboBox, ICustomerComboBox {
private readonly CustomerComboBoxPresenter presenter;
public CustomerComboBox() {
presenter = new CustomerComboBoxPresenter(this);
}
protected override void OnLoad() {
if (!Page.IsPostBack) presenter.HandleFirstLoad();
}
// Primary interface used by web page developers
public Guid ClientId {
get { return new Guid(SelectedItem.Value); }
set { SelectedItem.Value = value.ToString(); }
}
// "Hidden" interface used by presenter
IEnumerable<CustomerDto> ICustomerComboBox.DataSource { set; }
}
演示者填充数据源,web页面开发人员永远不需要知道它的存在。
但这不是银炮弹
我不建议总是使用显式接口实现。这只是它们可能有用的两个例子。
实现接口的每个类成员都导出一个语义上类似于VB的声明。NET接口声明被编写,例如:
Public Overridable Function Foo() As Integer Implements IFoo.Foo
尽管类成员的名称经常与接口成员的名称相匹配,而且类成员通常是public的,但这些都不是必需的。你也可以声明:
Protected Overridable Function IFoo_Foo() As Integer Implements IFoo.Foo
In which case the class and its derivatives would be allowed to access a class member using the name IFoo_Foo, but the outside world would only be able to access that particular member by casting to IFoo. Such an approach is often good in cases where an interface method will have specified behavior on all implementations, but useful behavior on only some [e.g. the specified behavior for a read-only collection's IList<T>.Add method is to throw NotSupportedException]. Unfortunately, the only proper way to implement the interface in C# is:
int IFoo.Foo() { return IFoo_Foo(); }
protected virtual int IFoo_Foo() { ... real code goes here ... }
没那么好。
除了前面提到的其他原因外,这是指一个类实现了两个不同的接口,而这两个接口的属性/方法具有相同的名称和签名。
/// <summary>
/// This is a Book
/// </summary>
interface IBook
{
string Title { get; }
string ISBN { get; }
}
/// <summary>
/// This is a Person
/// </summary>
interface IPerson
{
string Title { get; }
string Forename { get; }
string Surname { get; }
}
/// <summary>
/// This is some freaky book-person.
/// </summary>
class Class1 : IBook, IPerson
{
/// <summary>
/// This method is shared by both Book and Person
/// </summary>
public string Title
{
get
{
string personTitle = "Mr";
string bookTitle = "The Hitchhikers Guide to the Galaxy";
// What do we do here?
return null;
}
}
#region IPerson Members
public string Forename
{
get { return "Lee"; }
}
public string Surname
{
get { return "Oades"; }
}
#endregion
#region IBook Members
public string ISBN
{
get { return "1-904048-46-3"; }
}
#endregion
}
这段代码编译和运行正常,但是Title属性是共享的。
显然,我们希望返回Title的值取决于我们是将Class1作为Book还是Person来处理。这时我们可以使用显式接口。
string IBook.Title
{
get
{
return "The Hitchhikers Guide to the Galaxy";
}
}
string IPerson.Title
{
get
{
return "Mr";
}
}
public string Title
{
get { return "Still shared"; }
}
注意,显式接口定义被推断为Public -因此您不能显式地将它们声明为Public(或其他)。
还要注意,您仍然可以拥有一个“共享”版本(如上所示),但虽然这是可能的,但这样一个属性的存在是值得怀疑的。也许它可以用作Title的默认实现——这样就不必修改现有的代码来强制转换Class1到IBook或IPerson。
如果你没有定义“共享的”(隐式的)Title, Class1的消费者必须先显式地将Class1的实例转换为IBook或IPerson——否则代码将无法编译。
除了已经提供的优秀答案之外,还有一些情况需要显式实现,以便编译器能够找出需要什么。以IEnumerable<T>为例,它可能会经常出现。
这里有一个例子:
public abstract class StringList : IEnumerable<string>
{
private string[] _list = new string[] {"foo", "bar", "baz"};
// ...
#region IEnumerable<string> Members
public IEnumerator<string> GetEnumerator()
{
foreach (string s in _list)
{ yield return s; }
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
这里,IEnumerable<string>实现了IEnumerable,因此我们也需要。但是等等,泛型和普通版本都实现了具有相同方法签名的函数(c#对此忽略了返回类型)。这是完全合法的。编译器如何解决使用哪个?它迫使您最多只有一个隐式定义,然后它就可以解决它需要解决的任何问题。
ie.
StringList sl = new StringList();
// uses the implicit definition.
IEnumerator<string> enumerableString = sl.GetEnumerator();
// same as above, only a little more explicit.
IEnumerator<string> enumerableString2 = ((IEnumerable<string>)sl).GetEnumerator();
// returns the same as above, but via the explicit definition
IEnumerator enumerableStuff = ((IEnumerable)sl).GetEnumerator();
PS: IEnumerable的显式定义中有一点间接的作用,因为在函数内部,编译器知道变量的实际类型是StringList,这就是它解析函数调用的方式。实现一些抽象层,一些。net核心接口似乎已经积累起来了。