2

我有一个如下所示的类定义:

public class SolrObj
{
[SolrUniqueKey("id")]
public int id { get; set; }

[SolrField("title")]
public string title { get; set; }

[SolrField("description")]
public string description { get; set; }

[SolrField("url")]
public string url { get; set; }
}

在一些可以访问 SolrObj 的代码中,我有这个:

SolrObj a = new SolrObj
{
    id = edit_id,
    title = textbox_title.Text,
    description = textbox_description.Text,
    url = textbox_url.Text,
};

但是,当上面的代码片段运行时,我得到一个 NullReferenceException 。我不明白这是怎么发生的,因为我正试图在那里定义它。a 是引发异常的空对象。我怎样才能解决这个问题?

很抱歉这个简单的问题。上面的相同片段在另一个函数的其他地方也可以使用,所以我在这里有点困惑。

编辑:我看到其中一个 Text 属性为 null 并导致此异常;感谢到目前为止的答案,对不起,我很愚蠢。我怎样才能解决这个问题?有没有办法可以在分配上测试 null 并给出一个空字符串?也许是三元运算符?

编辑2:顺便说一句,这是一个不好的问题。我截断了要在此处发布的类,并排除了使用 element.SelectedItem.Text 的元素。SelectedItem 是 null 值,是让我们绊倒的事情——下面的评论者质疑 TextBox 的 Text 为 null 是正确的,这不是 null 也不应该为 null,这是混淆的一部分。空的东西是 element.SelectedItem (测试数据没有选择元素)。很抱歉造成混乱,再次感谢您的帮助。

4

4 回答 4

6

你确定 textbox_title、textbox_description 和 textbox_url 都是非空的吗?

Text属性为 null 不会在对象创建时导致 null 引用异常,只有当这些变量之一实际上为 null 时。从他们的名字来看,他们不应该是。如果由于某种原因它们可能为空,您将不得不求助于

(textbox == null ? "" : textbox.Text);

但是,如果它们都存在但Text可能为 null,则可以使用 null 合并运算符:

textbox.Text ?? ""
于 2011-02-03T02:05:54.867 回答
3

您的源变量之一为空:

textbox_title
textbox_description
textbox_url

因此,当您尝试引用它的 .Text 属性时,它会引发 Object Reference not set 异常,因为 (null).Text 不是有效的表达式。

如果它为空,那么您可能还有其他错误,可能在您的 .aspx/.ascx 上。因为通常,如果您的标记正确,您会期望 TextBox 存在。

要检查 null 使用这个:

SolrObj a = new SolrObj
{
    id = edit_id,
    title = textbox_title != null ? textbox_title.Text : string.Empty,
    description = textbox_description != null ? textbox_description.Text : string.Empty,
    url = textbox_url != null ? textbox_url.Text : string.Empty,
};

但我强烈怀疑您还有其他问题,因为如前所述,您不会期望 TextBox 为空。

您说它可以在其他地方使用-您是否可能复制了代码,但没有复制标记?<asp : TextBox id="textbox_title">你的表格上真的有一个吗?

于 2011-02-03T02:06:04.637 回答
1

你需要在使用它之前检查 null

if(edit_id != null & textbox_title!-= null & textbox_description!= null & textbox_url!=null)
{
SolrObj a = new SolrObj
{
    id = edit_id,
    title = textbox_title.Text,
    description = textbox_description.Text,
    url = textbox_url.Text,
};
}
于 2011-02-03T02:09:31.847 回答
1

要解决其他人指出的问题:

SolrObj a = new SolrObj
{
    id = edit_id,
    title = textbox_title != null ? textbox_title.Text : "",
    description = textbox_description != null ? textbox_description.Text : "",
    url = textbox_url != null ? textbox_url.Text : "",
};
于 2011-02-03T02:16:05.817 回答