为什么下面的代码没有在 C# 中返回预期的输出?

Why does the below code not returning the expected output in C#?

我想使用静态方法使对象为空。为了便于解释,我创建了一个示例代码 -

class Program
{
    static void Main(string[] args)
    {
        Car car = new Car();
        car.Name = "Audi";
        makeNull(car);
        Console.WriteLine(car.Name);

        Console.ReadKey();
    }

    static void makeNull(Car c)
    {
        c = null;
    }
}

class Car
{
    public string Name;
}

//输出-奥迪

我原以为上面的代码会出现 Null Exception,但出人意料地得到了“Audi”作为输出。任何人都可以解释为什么它会这样吗?

如果不将引用声明为 ref,则不能操作引用本身。因此这应该有效:

static void MakeNull(ref Car c)
{
    c = null;
}

MakeNull(ref car);

请注意,您可以修改引用指向的数据,因此这将给出输出“VW”:

static void MakeNull(Car c)
{
    c.Name = "VW";
}