【问题标题】:NullReferenceException in 'if' statement C#'if' 语句 C# 中的 NullReferenceException
【发布时间】:2015-04-28 04:47:30
【问题描述】:

这是一个字符串数组和字符串操作的简单程序。

我有一个名为 list 的字符串数组,其中的字符串代表我之前读取的文件的单行(每行包含 DNA 化学序列,如 AGCTTTTCATTCT)。

这个getStrands() 方法应该取出每一行(这是list 中的一个元素),其中包含一个名为sequence 的所需子字符串(如“CATCCT”),并将所有这些行与序列到另一个名为result 的字符串数组中并返回它。

    public static string[] getStrands(string[] list, string sequence)
        {
            List<string> temp = new List<string>();
            for (int i = 0; i < list.Length; i++)
            {
                string x = list[i];
                if (x.IndexOf(sequence) != -1)
                    temp.Add(x);
            }

            //converts temp List into a string[] to return
            string[] result = new string[temp.Count];
            for (int i = 0; i < temp.Count; i++)
                result[i] = temp.ElementAt(i);

            return result;
        }

错误: System.NullReferenceException 未处理 H结果=-2147467261 Message=对象引用未设置为对象的实例。

错误出现在这一行:if (x.IndexOf(sequence) != -1)

我检查了xsequence 是否为null,但它们不是。为什么当我尝试查看 x 是否包含 sequence 时,它给了我这个错误(我也尝试了 Contains() 方法,它给了我同样的错误)?

【问题讨论】:

标签: c# string contains indexof


【解决方案1】:

正如吉列尔莫所说,您应该在访问这些项目之前检查null

public static string[] getStrands(string[] list, string sequence)
{
    if (list == null) {
        return null;
    }
    List<string> temp = new List<string>();
    for (int i = 0; i < list.Length; i++)
    {
        if (list[i] != null) {
            string x = list[i];
            if (x.IndexOf(sequence) != -1)
                temp.Add(x);
        }
    }

    //converts temp List into a string[] to return
    string[] result = new string[temp.Count];
    for (int i = 0; i < temp.Count; i++)
        result[i] = temp.ElementAt(i);

    return result;
}

【讨论】:

    【解决方案2】:

    在代码上,您不检查 list 是否为 null (这会抛出 for (int i = 0; i &lt; list.Length; i++) 行,也不会检查每个元素的 null ,这会抛出您在问题中所说的行.

    【讨论】:

    • 非常感谢!我添加了一个 if 语句:if (x == null) continue; 来检查是否为空。它奏效了。
    • 如果答案有帮助,请选择此作为最有帮助的答案!
    • 我与通过引用获取参数的函数一起使用的一种机制(任何object 都考虑了它)是实际抛出ArgumentNullExceptionArgumentException... 取决于输入的情况预计不会为空。检查它的一种简单方法是问自己“输入为空是否有效?如果输入为空,函数应该如何表现?”,如果答案是“输入不应该为空”,则抛出,否则相应地编码。欢迎来到 Stack Overflow,如果答案对您有帮助,请点击左侧的检查 =)
    • @GuillermoMestre 引用类型在 C# 中默认通过引用传递。除非使用 refout 修饰符,否则引用在 C# 中按值传递。
    • @PrestonGuillot 你是对的,我想说“任何引用类型的参数”,但反过来说。昨天绝对不是我的一天:P
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多