2009-10-09 57 views
0

我有一個控件繼承自另一個控件(TxTextControl)。我有一個SelectedText屬性,基本上包裝基本SelectedText屬性,這顯然是需要的,因爲我的控件正在實現與該屬性的接口。代碼是這樣的:對象形式的設計時錯誤

public string SelectedText 
{ 
    get 
    { 
    return base.Selection.Text; // Error here (#1042) 
    } 
    set 
    { 
    if (base.Selection == null) 
    { 
     base.Selection = new TXTextControl.Selection(0, 0); 
    } 
    base.Selection.Text = value; 
    } 
} 

當我把這個控件放在窗體上時,沒有問題。它編譯並運行。一切看起來不錯。然而,當我保存,關閉然後重新打開表單,表單設計器顯示此錯誤:

Object reference not set to an instance of an object.
1. Hide Call Stack

at Test.FormattedTextBox2.get_SelectedText() in C:\Projects\Test\FormattedTextBox2.cs:line 1042

任何人都知道是怎麼回事?我即將拔掉我的最後一縷頭髮......

更新:
darkassisin93的答案並不完全正確,但那是因爲我發佈的代碼並不完全正確。在嘗試訪問該對象的屬性之前,我需要測試base.Selection是否爲null。無論如何,這個答案讓我朝着正確的方向前進。下面是實際的解決方案:

public string SelectedText 
{ 
    get 
    { 
    string selected = string.Empty; 
    if (base.Selection != null) 
    { 
     selected = base.Selection.Text; 
    } 
    return selected; 
    } 
    set 
    { 
    if (base.Selection == null) 
    { 
     base.Selection = new TXTextControl.Selection(0, 0); 
     // Have to check here again..this apparently still 
     // results in a null in some cases. 
     if (base.Selection == null) return; 
    } 
    base.Selection.Text = value; 
    } 
} 
+0

你可以發佈FormattedTextBox2.cs的內容,特別是第1042行嗎? – 2009-10-10 00:03:55

+0

已更新的問題表明錯誤與發佈的代碼有關,並且該行發生。 – 2009-10-10 00:09:45

回答

2

嘗試

return base.SelectedText ?? string.Empty; 

這很可能是因爲基類的SelectedText屬性設置爲null更換

return base.SelectedText; 

+0

謝謝。這沒有做到,但它讓我朝着寫作方向前進。我會更新我的問題以反映實際的解決方案。這確實是一個空的問題,一旦我得到了測試,現在它的工作。 – 2009-10-10 00:30:31