“对象未设置...”在对象创建
我有一个类定义是这样的:“对象未设置...”在对象创建
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是抛出异常的空对象。我怎样才能解决这个问题?
对不起,容易的问题。上面的同一个代码片段在另一个函数的其他地方工作,所以我在这里感到困惑。
编辑:我看到其中一个文本属性为空并导致此异常;感谢迄今为止的答案,对不起我很笨。我怎样才能解决这个问题?有没有一种方法可以在赋值时测试null,并给出一个空字符串?也许是三元操作符?
编辑2:顺便说一下,这是一个糟糕的问题。我截断了这里发布的类并排除了使用element.SelectedItem.Text的元素。 SelectedItem是空值,让我们触动的东西 - 下面质疑TextBox的Text为空的评论者是正确的,这不是null,并且不应该为null,这是混淆的一部分。 null是element.SelectedItem(测试数据没有选择元素)。对不起,感到困惑,并再次感谢您的帮助。
一个源变量为空:
textbox_title
textbox_description
textbox_url
所以,当你尝试引用它。文本属性则抛出一个对象没有设置例外,因为(空)。文本不是有效的表达。
如果它为空,那么你可能有一些其他错误,可能在你的.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,
};
但我强烈怀疑你有别的东西错了,因为之前说过你不希望一个文本框为空。
你说它可以在其他地方工作 - 你有可能复制了代码,但不是标记?你的表单上实际上是否有<asp : TextBox id="textbox_title">
?
其中一个是null,你是对的,谢谢。看到我上面的编辑;我需要一种方法来实例化对象,即使其中一个属性为null。 – jeffcook2150 2011-02-03 02:15:13
你确定textbox_title,textbox_description和textbox_url都是非空吗?
Text
的Text
属性不会在创建对象时引发空引用异常,只有当其中一个变量实际上为null时才会引发空引用异常。从他们的名字来看,他们不应该是。如果可能,出于某种原因,为空,你将不得不求助于
(textbox == null ? "" : textbox.Text);
然而,如果他们都存在,但Text
可能为空,你可以使用空合并运算符:
textbox.Text ?? ""
其中之一是null,你是对的,谢谢。看到我上面的编辑;我需要一种方法来实例化对象,即使其中一个属性为null。 – jeffcook2150 2011-02-03 02:12:50
谢谢,我用你的三元组作为违规的作品。请参阅上面编辑中的说明。我投了你一票,但是通过接受 jeffcook2150 2011-02-03 02:30:13
你需要使用它
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,
};
}
要解决的是其他人所指出的问题之前,要检查空:
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 : "",
};
是,`element.SelectedItem`将是无效的,如果选择了就没事下拉框。这比TextBox为null更有意义。 – 2011-02-03 03:24:44