【问题标题】:Missing operand after 'L' operator'L' 运算符后缺少操作数
【发布时间】:2016-06-30 13:14:32
【问题描述】:

我的代码出现以下错误:

“L”运算符后缺少操作数。

我调试了代码,发现它发生在下面一行:

DataRow[] documents = this.DataSet.Results_Documents.Select(String.Format("DocumentControlNumber = '{0}'", dcn), null, DataViewRowState.CurrentRows);

当 dcn 在其完整字符串中包含' 时,就会发生这种情况。

这究竟是什么原因?

例如:dcn :- Sheldon 的 Nat'l Bk

【问题讨论】:

  • dcn?? 的示例值?
  • 为什么文档 number 会包含撇号?是否需要将单引号替换为两个单引号才能转义?

标签: c#


【解决方案1】:

当 dcn 在其完整字符串中包含' 时,就会发生这种情况。

是的;使用连接的常见问题;让我们使用示例dcn 作为您问题中的Nat'l Bk of Sheldon;现在的查询是:

DocumentControlNumber = 'Nat'l Bk of Sheldon'

格式错误。由于这不允许正确的参数化,您需要“转义”该值;如果我不得不猜测,请选择以下之一:

DocumentControlNumber = 'Nat''l Bk of Sheldon'

DocumentControlNumber = 'Nat\'l Bk of Sheldon'

(注意\n C# also 需要转义,或使用逐字字符串文字)

两者都应该可以通过string.Replace 实现;例如dcn.Replace("'","''")(在string.Format的参数中)。

【讨论】:

    【解决方案2】:

    Select 要求字符串采用特定格式,当您拥有' 时,该字符串不再有效。您需要通过将每个 ' 替换为 '' 来转义引号

    DataRow[] documents = this.DataSet.Results_Documents.Select(
                                String.Format("DocumentControlNumber = '{0}'"
                                             , dcn.ToString().Replace("'", "''")
                                ), null, DataViewRowState.CurrentRows);
    

    如果dcnstring,则不需要.ToString()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 2011-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      相关资源
      最近更新 更多