c# - for循环的逻辑错误在哪里

标签 c# for-loop concatenation

public class Client
{
    public string nome;
}

Client j, h, m, n;
j = h = m = n = new Client();

Client[] c= new Client[]{j,h,m,n};
int[] n = new int[c.Length];

for (int i = 0; i < c.Length; ++i)
{
    n[i] =i;
    c[i].nome = "Client"+i;

}

n = 0,1,2,3的输出中;

但在 c = Client4,Client4,Client4,Client4 的输出中

我不是编程的新生,但我不明白为什么它没有连接每个 i 值。 我无法向自己解释。有 c[i],它应该可以工作。

有人可以帮忙吗?

最佳答案

代码:

j = h = m = n = new Client();

创建 jhmn单个 新对象。

因此,行 c[i].nome = "Client"+i; 将设置该单个对象的 nome 字段,覆盖所有已经完成的更改通过循环的先前迭代对其进行处理。换句话说,你拥有的是:

 j ---+
      |    +-------------+
 h ---+--> | single item |
      |    +-------------+
 m ---+
      |
 n ---+

如果你想要不同的对象,你需要使用类似的东西:

j = new Client();
h = new Client();
m = new Client();
n = new Client();

这样,当您更改其中一个对象时,它不会影响其他对象:

      +------+         +------+
j --> | item |   h --> | item |
      +------+         +------+
      +------+         +------+
m --> | item |   n --> | item |
      +------+         +------+

顺便说一句,如果您正在寻找一种资源大小有效的方式来执行此操作(从您的评论来看似乎就是这种情况),您可以尝试摆脱中间人。

不需要那些 j/h/m/n 临时引用,也没有 真正 无论如何使用单字符变量名的借口。嗯,除了 i,当然 :-)

那会是这样的:

Client[] clientArray = new Client[] {
    new Client(), new Client(), new Client(), new Client()
};
int[] numArray = new int[clientArray.Length];
for (int i = 0; i < clientArray.Length; ++i) {
    numArray[i] = i;
    clientArray[i].nome = "Client" + i;
}

关于c# - for循环的逻辑错误在哪里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50942698/

相关文章:

c - 在较大的字符串中查找子字符串的第一个字符的位置

r - For循环日期不丢失日期格式

算术加法和字符串连接之间的Java '+'运算符?

mysql - 在mysql存储过程中使用concat创建json

c# - 应用程序无法在三星 S6 中运行

c# - 如何围绕其中心旋转 3D 模型?

c# - 如何更快地加载多个网格

C# + WinRT + 用于网络(Azure 移动服务)操作的 Monogame 线程

java - 字符串数组的组合

r - 如何制作根据条件跨列多次连接的 R 循环