我看《我是誰?[C#]》

來源:互聯網
上載者:User

這幾天正在學習有關介面的知識,看到部落格園期刊上刊登了一篇名為《我是誰?[C#]》的文章,作者用生動有趣的語言對介面進行了深入的分析,感覺非常不錯。看完後也想發表一點自己的看法,但是沒法在期刊上回複,就寫在這兒了。

介面是一個公開的約定,利用介面可以實現與未知的代碼用一種通用的方法進行通訊。介面定義了自己的成員卻不提供任何實現,當然也無法被執行個體化。

當一個類繼承某個介面時,這個類就理所當然的有了實現介面所規定的全部成員的義務。至於這個類還能不能幹點其他的事,介面非常開明,它可能在說“這些我不管,只要你能幹完我要求的活就行。”,所以,從介面繼承的類完全可以具有其他非常多的功能,而這一切甚至與介面沒有關係,正如原文樣本中的N()。

再回到原文:
 有一個 interface ABC 包括了如下的方法 M():


public interface ABC
{
    void M();
}

      另外有個類 Class1 繼承了 ABC 並且擁有自己的方法 N():

public class Class1 : ABC
{
    public Class1(){}

    public void M()
    {
        Console.WriteLine("Now we are in Class1, using method which inherit from Interface ABC ");
    }

    public void N()
    {
        Console.WriteLine("Now we are in Class1, we used method which not inherit from Interface ABC ");
    }
}

看看M()到底屬於誰,從Class1的代碼看,毫無疑問,M()是Class1的一個公用方法,比較特殊的是,M()比較能幹,它同時擔負起了為ABC實現M()的義務。

當我們聲明:ABC t = new Class1(); 的時候,我們一定是想使用ABC的功能,而不是Class1,否則我想一定會改成這樣的: Class1 t=new Class1(); 雖然我們確確實實new了一個Class1,但我們new出來的對象還同時是ABC,Class1隻是在幕後為ABC做了實現而已,至於Class1還能做什麼,我們根本無從得到。開明的ABC自然不會把Class1的功能全盤托出,否則你直接找Class1得了。

事實上,我們完全可以讓Class1的一個方法去實現ABC,而這個方法不必公開,Class1甚至可以擁有一個同名的方法M()去做自己的事情。看下面的代碼:

 1public class Class1:ABC
 2{
 3    public void M()
 4    {
 5        Console.WriteLine("Now we are in Class1, But using method which not inherit from Interface ABC ");
 6    }
 7
 8    void ABC.M()
 9    {
10        Console.WriteLine("Now we are in Class1, using method which inherit from Interface ABC ");
11    }
12
13    public void N()
14    {
15        Console.WriteLine("Now we are in Class1, we used method which not inherit from Interface ABC ");
16    }
17}
18

現在再進行如下調用:

1ABC t = new Class1();
2t.M();

可以想到的結果自然是:Now we are in Class1, using method which inherit from Interface ABC

而如果調用改成:

1   Class1 t2=new Class1();
2t2.M();

結果將會是:Now we are in Class1, But using method which not inherit from Interface ABC

顯然,編譯器非常明晰的分清了實現ABC的M()與Class1自己的M()。現在反過來想一想,我們怎麼能要求用ABC聲明的t去實現N()呢。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.