gpt4 book ai didi

C# 字符串连接问题为什么 += 不能在这里工作?

转载 作者:太空宇宙 更新时间:2023-11-03 17:07:30 26 4
gpt4 key购买 nike

我有以下 C# 代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringTest
{
class Program
{
static void Main(string[] args)
{

String strSQLCode;
strSQLCode = " select rank() over (order by percentagecorrect desc, totalmilliseconds asc) as rank, * "
+= " from view_dg_game_details gd (nolock) "
+= " where gd.gametypeid = {0} "
+= " and gd.numberofrounds = {1} "
+= " and gd.gamevalues = '{2}' ";
}
}
}

出于某种原因,我收到错误消息“赋值的左侧必须是变量、属性或索引器”。

我看不出错误试图告诉我什么。我已经注释掉了有问题的行,但错误只是向上移动了一行。

我可以使用此方法使字符串连接正常工作:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StringTest
{
class Program
{
static void Main(string[] args)
{

String strSQLCode;
strSQLCode = " select rank() over (order by percentagecorrect desc, totalmilliseconds asc) as rank, * ";
strSQLCode = strSQLCode + " from view_dg_game_details gd (nolock) ";
strSQLCode = strSQLCode + " where gd.gametypeid = {0} ";
strSQLCode = strSQLCode + " and gd.numberofrounds = {1} ";
strSQLCode = strSQLCode + " and gd.gamevalues = '{2}' ";
}
}
}

谁能给我解释一下这个错误是怎么回事?

谢谢

最佳答案

因为你不能在不重复你正在操作的变量的情况下将 += 运算符串在一起:

strSQLCode = @"select rank() over (order by percentagecorrect desc, 
totalmilliseconds asc) as rank, * ";
strSQLCode += " from view_dg_game_details gd (nolock) ";
strSQLCode += " where gd.gametypeid = {0} ";
strSQLCode += " and gd.numberofrounds = {1} ";
strSQLCode += " and gd.gamevalues = '{2}' ";

如果你想将它声明为“长”单行,只需使用 +

strSQLCode = @"select rank() over (order by percentagecorrect desc, 
totalmilliseconds asc) as rank, * "
+ " from view_dg_game_details gd (nolock) "
+ " where gd.gametypeid = {0} "
+ " and gd.numberofrounds = {1} "
+ " and gd.gamevalues = '{2}' ";

或者,如果您不需要这些,您可以只使用一个字符串文字:

strSQLCode = 
@"select rank() over (order by percentagecorrect desc,
totalmilliseconds asc) as rank, *
from view_dg_game_details gd (nolock)
where gd.gametypeid = {0}
and gd.numberofrounds = {1}
and gd.gamevalues = '{2}' ";

关于C# 字符串连接问题为什么 += 不能在这里工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9282487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com