C#中的 隐式与显式接口实现
在C#中,正常情況下使用接口的實現(xiàn)使用的是 隱式接口實現(xiàn)。
public interface IParent1 {void Medthod(); }public class Child : IParent1 {public void Medthod(){Console.WriteLine("Child 中的實現(xiàn)方法");} }C# 編譯器假定Child中的Medthod的方法是對接口IParent1中Medthod方法的時候。C#編譯器之所以這樣做出假定,是因為Medthod方法的可訪問性是public,而且接口方法的簽名和新引入的方法完全一致。也就是說兩個方法具有相同的參數(shù)和返回類型。如果新的Test方法被標記為virtual,C#編譯器仍會認為該方法匹配與接口方法。
?
C# 會將新方法的實現(xiàn)和接口的實現(xiàn)認為是同一種實現(xiàn)。
static void Main(string[] args) {Child child = new Child();child.Medthod();IParent1 test1 = child;test1.Medthod();Console.ReadKey(); }因為方法的實現(xiàn)和接口的實現(xiàn)被認定為同一種方法,那輸出的結果就是一樣的。
?
將定義那個接口名稱作為方法名的前綴,例如上面的IParent1.Medthod()。創(chuàng)建的就是一個?顯式接口方法實現(xiàn)(Explicit Interface Method Implementation ,EIMI)。注意,在C#中定義一個顯式接口方法時,不允許指定可訪問性(public或者private等)。否則編譯器匯報錯誤,例如下圖。
顯式接口的實現(xiàn)類默認是private,防止其他類直接使用實例中的方法,只能通過接口來調(diào)用。EIMI的方法也不能標記為virtual,所以他不能重寫。這是因為EIMI方法并非真的是類型對象模型的一部分,它是將一個接口(一組行為或者方法)連接到一個類型上,同時避免公開行為/方法的一種方式。所以使用類對象也不能點出改方法。
?
接口類在調(diào)用方法時,使用的也是顯式實現(xiàn)中的實現(xiàn)。?
static void Main(string[] args) {Child child = new Child();child.Medthod();IParent1 test1 = child;test1.Medthod();Console.ReadKey(); }public interface IParent1 {void Medthod(); }public class Child : IParent1 {public void Medthod(){Console.WriteLine("Child 中的實現(xiàn)方法");}void IParent1.Medthod(){Console.WriteLine("顯式實現(xiàn)的IParent的方法");} }?輸出的結果:
?
參考博客:https://blog.csdn.net/u010533180/article/details/72954192
轉載于:https://www.cnblogs.com/gp112/p/10744757.html
總結
以上是生活随笔為你收集整理的C#中的 隐式与显式接口实现的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 工具资源系列之给mac装个虚拟机
- 下一篇: 软件工程——结对编程第一次作业