C# 为什么我可以将项目添加到列表中,但不能重新分配它?

C# 为什么我可以将项目添加到列表中,但不能重新分配它?,c#,C#,这可能是一个很难回答的问题,但我无法完全理解为什么我可以将项目添加到列表中,为什么我不能将其设置为null public class Test { public List<string> Source { get; set; } public Test() { this.Source = new[] { "Hey", "hO" }.ToList(); } } class Program { static void Main(string[] args

这可能是一个很难回答的问题,但我无法完全理解为什么我可以将项目添加到列表中,为什么我不能将其设置为null

public class Test
{
    public List<string> Source { get; set; }
    public Test()
    { this.Source = new[] { "Hey", "hO" }.ToList(); }
}

class Program
{
    static void Main(string[] args)
    {
        Test test = new Test();
        ModifyList(test.Source);
        //Why here test.Source.Count() == 3 ? Why isn't it null ?
    }

    private static void ModifyList(List<string> list)
    {
        list.Add("Three");
        list = null;
    }
}
公共类测试
{
公共列表源{get;set;}
公开考试()
{this.Source=new[]{“嘿”,“hO”}.ToList();}
}
班级计划
{
静态void Main(字符串[]参数)
{
测试=新测试();
修改列表(测试源);
//为什么这里test.Source.Count()==3?为什么不是空值?
}
私有静态无效修改列表(列表)
{
列表。添加(“三”);
列表=空;
}
}
为什么在调用ModifyList之后,test.Source.Count()==3?为什么它不是空的

我希望列表要么为空,要么保持两个元素不变

有人能给我解释一下发生了什么事吗? 多谢各位

这是一种卑鄙的行为。您正在将
list
设置为指向
null
,而不是原始列表

您应该使用
ref
关键字来修改原始变量

class Program
{
    static void Main(string[] args)
    {
        Test test = new Test();
        ModifyList(ref test.Source);
        //Why here test.Source.Count() == 3 ? Why isn't it null ?
    }

    private static void ModifyList(ref List<string> list)
    {
        list.Add("Three");
        list = null;
    }
}
类程序
{
静态void Main(字符串[]参数)
{
测试=新测试();
修改列表(参考测试源);
//为什么这里test.Source.Count()==3?为什么不是空值?
}
专用静态无效修改列表(参考列表)
{
列表。添加(“三”);
列表=空;
}
}

通过执行
list=null将新值分配给本地标识符
列表
。您不会更改(删除)以前存储在其中的对象。

在此方法中

private static void ModifyList(List<string> list)
私有静态无效修改列表(列表)
列表
参数是按值传递的引用。您正在添加到引用的列表中,这是一个正常操作。然后将by valye copy设置为
null
。但是原始参考(
test.Source
)保持不变


在所有代码中,只有一个
List
实例,但在不同的时间有多个引用指向它

您正在将
list
参数传递给方法,并在方法体中将其设置为null,这不会影响
test.Source
。要影响
test.Source
您必须通过ref
ModifyList(ref List)
通过它。谢谢,这就是我想要的答案“您正在添加到引用列表,这是一个正常操作”