difference b/w implicitly implementing a member and explicitly implementing a member in C#
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
C#: Interfaces - Implicit and Explicit implementation
我在读关于界面重新实现的文章。我不确定这是什么意思?"隐式实现成员和显式实现成员"
样例代码:
显式成员实现:
1 2 3 4 5 6 7 8 9 | public interface IUndoable { void Undo(); } public class TextBox : IUndoable { void IUndoable.Undo() { Console.WriteLine ("TextBox.Undo"); } } public class RichTextBox : TextBox, IUndoable { public new void Undo() { Console.WriteLine ("RichTextBox.Undo"); } } |
隐式成员实现:
1 2 3 4 | public class TextBox : IUndoable { public void Undo() { Console.WriteLine ("TextBox.Undo"); } } |
显式接口实现允许您实现具有相同签名的成员的不同接口。它还允许您隐藏接口实现(实现的成员只能通过引用接口类型来使用):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public interface IUndoable { void Undo(); } public interface IVeryUndoable { void Undo(); } public class TextBox : IUndoable, IVeryUndoable { void IUndoable.Undo() { Console.WriteLine ("TextBox.Undo"); } void IVeryUndoable.Undo() { Console.WriteLine ("TextBox.VeryUndo"); } } |
在这种情况下,您有两个具有相同签名的方法
1 2 | IUndoable undoable = (IUndoable)textbox; undoable.Undo(); // now member available |
为什么要隐藏一些接口实现?保持对象API更干净。来自.NET的示例:
与