【发布时间】:2019-06-01 19:55:50
【问题描述】:
我有一件奇怪的事情,我正在做的一些代码同时修改了副本和原始列表。我已经尽可能地将问题归结为仅在单个文件中显示错误。虽然我在现实世界中的例子要复杂得多.. 但归根结底,这一切都是问题所在。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestingRandomShit
{
class Program
{
private static string rawInput;
private static List<string> rawList;
private static List<string> modifiedList;
static void Main(string[] args)
{
rawInput = "this is a listing of cats";
rawList = new List<string>();
rawList.Add("this");
rawList.Add("is");
rawList.Add("a");
rawList.Add("listing");
rawList.Add("of");
rawList.Add("cats");
PrintAll();
modifiedList = ModIt(rawList);
Console.WriteLine("\n\n**** Mod List Code has been run **** \n\n");
PrintAll();
}
public static List<string> ModIt(List<string> wordlist)
{
List<string> huh = new List<string>();
huh = wordlist;
for (int i = 0; i < huh.Count; i++)
{
huh[i] = "wtf?";
}
return huh;
}
//****************************************************************************************************************
//Below is just a print function.. all the action is above this line
public static void PrintAll()
{
Console.WriteLine(": Raw Input :");
Console.WriteLine(rawInput);
if (rawList != null)
{
Console.WriteLine("\n: Original List :");
foreach (string line in rawList)
{
Console.WriteLine(line);
}
}
if (modifiedList != null)
{
Console.WriteLine("\n: Modified List :");
foreach (string wtf in modifiedList)
{
Console.WriteLine(wtf);
}
Console.ReadKey();
}
}
}
}
基本上,我有三个变量....一个字符串和两个列表。原始代码对字符串进行了一些标记,但对于这个演示,我简单地使用 List.Add() 来伪造它以使其易于阅读。
所以我现在有一个字符串和一个列表,每个元素中都有一个单词。
这是我不明白的令人困惑的部分。我知道它与参考有关,但我不知道如何适应它。
我有一个方法叫做 ModIt()... 它简单地接受一个 List 然后创建一个名为 huh 的全新 List,将原始列表复制到新列表上,然后将 huh 中的每一行更改为“wtf? ”。
现在据我了解.. 我应该以 3 个变量结束...
1) 一个字符串 2) 每个元素中包含不同单词的 List 3)一个长度相同的列表,每个元素都是“wtf?”
但是,发生的情况是我尝试打印出两个列表,它们都将每个元素都设置为“WTF?”....所以是的.. wtf man?我超级困惑。我的意思是在 ModIt 中,我什至构建了一个全新的字符串,而不是修改正在传递的字符串,但它似乎没有任何影响。
这是输出...
:原始输入:这是猫的列表
:原始列表:这是猫的列表
**** 模组列表代码已运行 ****
:原始输入:这是猫的列表
:原始列表:wtf?什么?什么?什么?什么?什么鬼?
:修改列表:wtf?什么?什么?什么?什么?什么鬼?
【问题讨论】:
-
这是因为
huh = wordlist;你在做reference copy
标签: c#