我使用一个将字符串保存到字符串数组中的函数 但2012年可视化显示此错误 对象引用未设置为对象的实例。
这是我的代码:
public void ShowLinkList(ref TreeNode t, ref string[] Data, ref int i)
{
string str;
if (t!= null)
{
ShowLinkList(ref t.LeftChild, ref Data, ref i);
Data[i] = CreatStr(t.Parent.Word) + "," + CreatStr(t.LeftChild.Word )+ "," + CreatStr(t.RightChild.Word) + "," + CreatStr(t.Word);
i++;
ShowLinkList(ref t.RightChild, ref Data, ref i);
}
}
public string CreatStr(string str)
{
if (str == "")
{
return "__";
}
return str;
}
当t为null时," if(t!= null)"不允许编译器调试 ,CreatStr(string)将空字符串转换为" __"在输出中(窗口形式C#) 这个metode(ShowLinkList)保存了t.parent.word& t.leftchild.word& t.rightchild.word&字符串数组中的t.word 请帮帮我。谢谢你
答案 0 :(得分:0)
首先,""
等于string.Empty
且不等于null
你没有对t的任何属性进行错误处理,所以如果其中任何一个为null,那么它就不知道Word
是什么,我建议至少在TreeNode
public bool HasValidBranches()
{
return Parent != null && LeftChild != null && RightChild != null;
}
然后将此添加到您已经存在的错误处理中,并随时修改以满足您的需求
if(t != null && t.HasValidBranches())
....
注意:您可以随时将额外的空值检查直接添加到当前代码中。