简体   繁体   English

当我将变量传递给另一种形式的C#时发生NullReferenceException

[英]NullReferenceException when I pass variables to another form C#

So I have the following situation; 所以我有以下情况; I want to send a couple of variables to another form. 我想将几个变量发送到另一种形式。 Here is some code: 这是一些代码:

// In Form1
Form3 f3 = new Form3();
f3.SetVariables(pieces);
// In Form3
string[] items;
void SetVariables(string[] array)
{
    items = array;
}

Now this does work but if I try to use: 现在这工作,但如果我尝试使用:

items[x].Length

It throws a NullReferenceException , but if I use: 它抛出NullReferenceException ,但是如果我使用:

String.IsNullOrEmpty(items[x]);

(I am checking to see if items[x] has a value) The above code works perfectly, with no errors. (我正在检查items[x]是否具有值)上面的代码运行完美,没有错误。 Is there a reason behind this? 这背后有原因吗?

Thanks! 谢谢!

String.IsNullOrEmpty will check for the variable being null in the first place. String.IsNullOrEmpty将首先检查变量是否为null。 Calling items[x].Length when items[x] is null will fail because there is no object to call .Length on items[x]为null时调用items[x].Length将失败,因为没有对象可以调用.Length

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM