【问题标题】:Inserting items in a List<>在 List<> 中插入项目
【发布时间】:2013-12-05 13:08:45
【问题描述】:

我正在尝试将用户构建查询的所有单词放入列表。

我做到了

if (columns[(a - 1)].Contains("$"))
{
    string[] splt1 = rows[b].Split('$');
    string userBuiltQuery = columns[(a - 1)].ToString();
    userBuiltQuery= userBuiltQuery.Replace("$", "");
    var pattern = new Regex(@"\w(?<!\d)[\w'-]*");
    foreach (Match m in pattern.Matches(userBuiltQuery))
    {
        words.Add(Convert.ToString(m));
    }
}
}

但在 foreach 循环中我得到一个错误提示。

Object reference not set to an instance of an object.

为什么会这样?

【问题讨论】:

  • Ehm...所以您问为什么带有List&lt;string&gt; words 的代码段以NullReferenceException 失败,但您不包括实例化words 列表的部分? :)
  • @PatrykĆwiek - 这可能是因为当单词 没有 实例化时会发生此错误,因此他无法显示他没有的代码;)
  • 我们能看到对象词的声明吗?

标签: c# arrays loops parameters


【解决方案1】:

在添加元素之前尝试将words 初始化为List&lt;string&gt; 的实例。

【讨论】:

  • 一种特殊的心灵感应 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-08
  • 2018-03-30
相关资源
最近更新 更多