the Differences between abstract class & interface in C#介面和抽象類別的區別

來源:互聯網
上載者:User

    abstract class and interface in C# look like much, but sometimes they get the similiar use. However, there are still much differences between them. here we go.
    抽象類別和介面初看上去很象,但是還是有很多區別的。
   a) Interface Grammar介面文法
   [public|protected|internal|private] interface interfaceName
    {
        public int add(int x,int y);
//this is error! interface memeber can not be described with any characters to declare its access attribute.
//介面中任何成員和屬性不能被任何修飾符修飾來表明其訪問屬性!
        int add(int x,int y);
//this is right!
        int Count{get;} //interface property介面屬性
        string this[int index]{get;set;}//index interface 介面索引
    }

    Difference:    
        1. in interface, all interface members can not be decorated with any other access tag,such as public,private.etc.
        2. in abtract class, such case is just on the opposite.
    
    b) abstract class Grammar 抽象類別文法
        [public|protected|internal|private] abstct class className
        {
            public abstract int add(int x,int y);
            //it's ok, but that forbidden in interface!
            //在abstract class中,類成員可以有各種修飾符。如果該類成員沒有被implement,那麼該類一定要被標示為abstact方法。否則出錯!當然也可以實現該方法。如下multiply方法所示
            public virtual int multiply(int x,int y)
            {
                return x*y;
            }
        }

        Difference:
        1.in interface, all interface memebers can not be implemented. and it's just an declaration  for other class which will inherented from it and implemented all of them.
        在介面中,所有介面成員都不能被實現,它只是一個申明而已,其他類繼承自該介面,並且要實現該介面中的所有成員。
        2 in abstract class, its member can be implemented ,otherwise must be decorated with abstract that is the same with interface . of course, any class inherented from this  must implemented all its abstract method. of course, u can also override the method that has already implemented method.
        在抽象類別中,其成員可以被實現,如果不實現的話,其方法成員一定要被標標示為abstract. 同時,任何繼承於該抽象類別的類必須要實現其所有標示為abstract的方法,這點與interface相同。或者該類也可以override該抽象類別中的method. 這一點interface絕對不可能,因為interface中根本沒有實現過,何來override?

        

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.