【问题标题】:"|" Operator inside c# string - how to escape it? [duplicate]“|” c# 字符串中的运算符 - 如何转义它? [复制]
【发布时间】:2015-10-15 17:19:52
【问题描述】:

我有以下字符串 - 这是执行 exe 的参数。

但我收到错误 - “运算符“|”不能应用于字符串和字符串类型的操作数。

我怎么能逃脱我的“|” ?我试过\,没用:(

string.Format(
                        @"-S -E -M -m -e ascii -i {0}.dat -T db1.dbo.table1 -R {1}.reject -t "|" -r \r\n -rt value -rv 1000 -W  -fh 0", 
                        saveFilePath + a,
                        saveFilePath + b);

【问题讨论】:

  • 你为什么不使用“字符串\|”而不是 @""|"" ?
  • 需要转义的不是|,而是双引号。使用双双引号。
  • 那我需要在开头保留“@”吗?
  • 我在没有@的情况下尝试过 - 但它给了我错误。

标签: c# string escaping


【解决方案1】:

@"..." 文字中,要拥有" 字符,您必须使用其中的两个。所以:

string.Format(
    @"-S -E -M -m -e ascii -i {0}.dat -T db1.dbo.table1 -R {1}.reject -t ""|"" -r \r\n -rt value -rv 1000 -W  -fh 0", 
// note -----------------------------------------------------------------^^-^^
    saveFilePath + a,
    saveFilePath + b);

但是,如果您希望 \r\n 成为回车符和换行符,则不能使用 @"..." 字符串文字,因为反斜杠在他们(这就是他们的全部意义)。所以如果是这样的话:

    string.Format(
        "-S -E -M -m -e ascii -i {0}.dat -T db1.dbo.table1 -R {1}.reject -t \"|\" -r \r\n -rt value -rv 1000 -W  -fh 0", 
// note ^-------------------------------------------------------------------^^-^^
        saveFilePath + a,
        saveFilePath + b);

推荐阅读:string (C# Reference)


旁注:不需要对函数参数进行字符串连接。由于您已经调用string.Format,您可以让这样做:

string.Format(
    "-S -E -M -m -e ascii -i {0}{1}.dat -T db1.dbo.table1 -R {2}{3}.reject -t \"|\" -r \r\n -rt value -rv 1000 -W  -fh 0", 
// note ---------------------^^^^^^--------------------------^^^^^^
    saveFilePath,
    a,             // <==
    saveFilePath,
    b);            // <==

【讨论】:

    猜你喜欢
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 2011-04-17
    • 2019-12-06
    相关资源
    最近更新 更多