我有一个从另一个控件(TxTextControl)继承的控件。我有一个SelectedText属性,basicaly封装了基本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;
}
}当我把这个控件放到表单上时,没有问题。它编译并运行。一切看起来都很好。但是,当我保存、关闭然后重新打开窗体时,表单设计器将显示以下错误:
对象引用未设置为对象的实例。
1.隐藏呼叫堆栈
在C:\Test.FormattedTextBox2.get_SelectedText\Test\FormattedTextBox2.cs:第1042行中
有人知道怎么回事吗?我要把最后一根头发拔出来.
更新:
darkassisin93 93的答案并不完全正确,但这是因为我发布的代码不完全准确。在尝试访问该对象的属性之前,我需要测试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;
}
}发布于 2009-10-10 00:11:53
试着替换
return base.SelectedText;使用
return base.SelectedText ?? string.Empty;这很可能是因为基类的SelectedText属性设置为null。
https://stackoverflow.com/questions/1546615
复制相似问题