2012-03-24 50 views
0

所以我試圖在我的代碼中實現一些繼承,因爲我有許多類需要與我作爲參數傳遞的其他類的相同實例,但是現在我遇到了一個遞歸問題,我不太明白爲什麼。繼承遞歸

它在ParentScreen類(這只是一個普通的類,沒有XAML)中斷 - 也許這不是解決我的簡單問題的最好方法嗎?

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     ParentScreen ps = new ParentScreen(); 
     container.Children.Add(ps.ms); 
    } 
} 

public class ParentScreen : UserControl 
{ 
    public MainScreen ms; 

    public ParentScreen() 
    { 
     ms = new MainScreen(); // breaks here 
    } 
} 

public partial class MainScreen : ParentScreen 
{ 
    public MainScreen() 
    { 
     InitializeComponent(); 
    } 
} 

<runtime:ParentScreen x:Class="WpfApplication1.MainScreen" 
     xmlns:runtime="clr-namespace:WpfApplication1" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
     Height="100" Width="200"> 
    <Grid> 
     <TextBox Height="23" Margin="12,12,0,0" Name="textBox1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="120" /> 
    </Grid> 
</runtime:ParentScreen> 
+1

創建父屏幕對象時,代碼會調用創建mainScreen對象的構造函數。由於MainScreen對象從ParentScreen繼承 - 您只需創建一個新的parentScreen對象,並因此再次調用parentScreen構造函數! - > StackoverflowExcepetion ?! – 2012-03-24 12:14:37

+0

哦,所以我...哎呀!感謝您指出了這一點! – Michael 2012-03-24 12:19:21

+1

你需要'改寫'解決方案(和問題) - 我。即這不是用WPF用戶控件處理重複使用的最快樂的方式,由於某種原因,最終會出現問題。這只是一個明顯的錯誤:),但你可能會遇到更多麻煩,難以發現。繼承不是GUI/WPF組件的最佳選擇,並且在WPF情況下並不是最好的。圍繞WPF,你最好通過MVVM嘗試和實現事物,例如用於各種控制的數據模板 - 並且僅作爲最後的手段訴諸自定義編碼控制 - 可以幫助你,引導你走向最好 – NSGaga 2012-03-24 12:36:20

回答

2

我覺得有兩個問題:

  • 你混合「實例」和「階級」的概念 當A繼承B,和你實例化一個新的A,那麼你只有一個A的實例,而不是2個實例(A & B)

  • 當繼承並放置默認的CTor時,自動調用基礎CTor。這意味着這樣的代碼:

    公共部分類MainScreen:ParentScreen { 公共MainScreen() { 的InitializeComponent(); }}

比同:

public partial class MainScreen : ParentScreen 
{ 
    public MainScreen() : base() 
    { 
     InitializeComponent(); 
    } 
} 

所以當你打電話

ParentScreen ps = new ParentScreen(); 

發生了什麼:

  • ParentScreen.CTor => MS =新的MainScreen(); ()因爲MainScreen繼承自 ParentScreen)=> ms = new MainScreen();}}
  • MainScreen.CTor => ParentScreen.CTor
  • ParentScreen.CTor => ms = new MainScreen();

等(無限廁所)

0

這應該是一個stackoverflowException?

當你創建一個子類時,首先會調用它的父類的構造函數。

using System; 

class Parent 
{ 
    private Client m_client; 
    public Parent() 
    { 
    m_client = new Client(); 
    Console.WriteLine("client inited"); 
    } 
} 

class Client: Parent 
{ 
    public Client() 
    { 
    //.. 
    } 
} 

class Test 
{ 
    public static void Main(string[] args) 
    { 
    Client c = new Client(); 
    Console.WriteLine("End"); 
    } 
} 

運行上面的代碼,它會在MacOS上運行Mono時導致un段錯誤。

檢查它在Windows中發生了什麼。

:)