Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/260.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如果我只更改一个列表,为什么所有列表(列表中)的值都会更改?_C#_List_Nested Lists - Fatal编程技术网

C# 如果我只更改一个列表,为什么所有列表(列表中)的值都会更改?

C# 如果我只更改一个列表,为什么所有列表(列表中)的值都会更改?,c#,list,nested-lists,C#,List,Nested Lists,我需要这样一个动态2D列表list。只要我更改了内部列表中的一个值,它就会更改所有内部列表中该位置的所有值 例如: 我在一个列表中有3个列表: Boolean t = true; Boolean f = false; List<Boolean> temp = new List<Boolean>(); List<List<Boolean>> list = new List<List<Boolean>>(); void cre

我需要这样一个动态2D列表
list
。只要我更改了内部列表中的一个值,它就会更改所有内部列表中该位置的所有值

例如:

我在一个列表中有3个列表:

Boolean t = true;
Boolean f = false;
List<Boolean> temp = new List<Boolean>();
List<List<Boolean>> list = new List<List<Boolean>>();

void createLists()
{
    for(int i=0; i<3; i++)
    {
        temp.Clear();
        for(int j=0; j<3; j++)
        {
            temp.Add(f);        //{f, f, f}
        }
        list.Add(temp);         //list[0] = {f, f, f}
    }                           //list[1] = {f, f, f}
}                               //list[2] = {f, f, f}
列表[0]
现在等于
{t,f,f}
列表[1]
列表[2]
应该仍然等于
{f,f,f}
,但相反
列表[1]
列表[2]
都是
{t,f,f}

所以我的矩阵是:

{{t, f, f},
 {t, f, f},
 {t, f, f}}
而不是:

{{t, f, f},
 {f, f, f},
 {f, f, f}}

如果我使用
列表[0],则会出现同样的问题

问题在于您的
temp
列表始终是同一个对象引用

Boolean t = true;
Boolean f = false;

List<List<Boolean>> list = new List<List<Boolean>>();

void createLists()
{
    for(int i=0; i<3; i++)
    {
        var temp = new List<Boolean>();
        for(int j=0; j<3; j++)
        {
            temp.Add(f);        
        }
        list.Add(temp);         
    }                           
}   
Boolean t=true;
布尔f=假;
列表=新列表();
void createLists()
{

对于(int i=0;i因为您只创建一个
列表
,所以您确实有一个对同一列表的多个引用的列表。您应该将
temp
的创建移动到第一个
for
循环
temp.Clear();
每次都将清除相同的列表。并且
List.Add(temp);
将添加相同的列表(覆盖)每次都列出。这两者都是因为
temp
是一个
list
,这是一个。将
temp
的声明移动到循环中,而不是使用
.Clear()
。因为您多次将相同的
temp
添加到
列表中。只需执行
tmp.Clear()
。这会从列表中删除所有元素,但不会创建新的元素。使用
temp=new list()
而不是
temp.Clear()
来创建新的lisr
Boolean t = true;
Boolean f = false;

List<List<Boolean>> list = new List<List<Boolean>>();

void createLists()
{
    for(int i=0; i<3; i++)
    {
        var temp = new List<Boolean>();
        for(int j=0; j<3; j++)
        {
            temp.Add(f);        
        }
        list.Add(temp);         
    }                           
}