Home > Backend Development > C#.Net Tutorial > C# List Value Change Demonstration and Explanation Passed as Parameter

C# List Value Change Demonstration and Explanation Passed as Parameter

高洛峰
Release: 2016-12-15 15:48:06
Original
2199 people have browsed it

[TestMethod]
public void TestMethod1()
{
    List<int> list = new List<int>();
    Test(list);
    Console.WriteLine(list.Count()); // 总数量变为 1
}

private void Test(List<int> list)
{
    list.Add(1);
}
Copy after login

You can find that after Test, the number of elements in the list has changed from 0 to 1.

If the variable list is assigned to another variable list2, the list will also change when list2 is operated.

This is because these variables actually point to another memory block, and changes to the number of elements and element values ​​all change the corresponding memory block.

But when their ConvertAll method is called, the returned variable points to another memory block, which is different from the previous one.

[TestMethod]
public void TestMethod1()
{
    List<int> list = new List<int>();
    Test(list);
    Console.WriteLine(list.Count()); // 总数量仍为 0
}

private void Test(List<int> list)
{
    List<int> list2 = new List<int>();
    list2.Add(1);
    
    list = list2;
}
Copy after login

The above code is different. This is list = list2, which actually points the list to the memory block corresponding to list2. According to the previous conclusion, the list in the parameter is the same as list2, not TestMethod1. A group of people in the list.

The following code is different, but now it actually creates two new List(), and no one in TestMethod1() uses it anymore.

[TestMethod]
public void TestMethod1()
{
    List<int> list = new List<int>();
    Test(ref list);
    Console.WriteLine(list.Count()); // 总数量变为 1
}

private void Test(ref List<int> list)
{
    List<int> list2 = new List<int>();
    list2.Add(1);
    
    list = list2;
}
Copy after login

The same is true for arrays.


For more C# List value change demonstration and explanation related articles, please pay attention to the PHP Chinese website!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template