2014-02-06 165 views
0

很抱歉,如果這是一個愚蠢的問題,但IM非常confuced我爲什麼要繼承?

namespace Test 
{ 
    public class Class1 
    { 
     public string property1 { get; set; } 
     public void method1() 
     { 

     } 
    } 

    public class Class2 : Class1 
    { 
     public void method2() 
     { 
      property1 = "set from Class2"; 
      method1(); 
     } 

    } 

    public class Class3 
    { 
     Class1 objClass1 = new Class1(); 
     public void method3() 
     { 
      objClass1.property1 = "set from Class3"; 
      objClass1.method1(); 
     } 

    } 
} 

如果我可以使用類class1, 的對象怎麼辦遺產繼承的優勢(如在做訪問的Class1從Class3中的所有公共方法Class2)?

+0

您正在尋求計算機科學課程。 –

+0

繼承或關聯取決於您的使用場景。 –

+1

半認真:如果您已經顯示過,沒有任何優勢......您無法真正改變'Class1'的行爲,因爲它沒有虛擬方法,並且您已經使用了C#中唯一的基類可能性。在這種情況下,通用接口可能會更好。 –

回答

0

In OOPs, the concept of inheritance provides the idea of reusability. This means that we can add additional features to an existing class without modifying it. This is possible by deriving a new class from the existing one. The new class will have combined features of both the classes.

  • 一旦行爲(方法)或屬性是在超類(基類)中所定義,該行爲或特性被所有的子類(派生類)自動繼承。

  • 通過繼承增加了代碼的可重用性。

  • 繼承提供了一個清晰的模型結構,它很容易理解,沒有很多複雜性使用繼承,類在分層樹結構中分組在一起。代碼易於管理並分爲父類和子類。

1

繼承的優點是class2展現了class1的所有屬性和方法。 您可以通過使用class2的對象來訪問class1的方法。

相關問題