将对象设置为 null 而不将其作为引用传递

sar*_*rat 2 c#

以下行为的 C# 语言规范是什么。属性的值将被保留,但新实例(空或新对象)不会更新为实际参数。除了更改它指向的对象之外,它基本上具有 ref 的功能。

主函数中的对象保持不变(不为空),但字符串属性已更改为“Hello World”

class Program
{
    class MyClass
    {
        public string str;
    }

    static void MyMethod(MyClass obj)
    {
        obj.str = "Hello World";
        obj = null;
    }

    static void Main(string[] args)
    {
        MyClass o = new MyClass();
        o.str = "Hello";
        Console.WriteLine(o.str);
        MyMethod(o);

        Console.WriteLine(o.str); // prints "Hello World"
    }
}
Run Code Online (Sandbox Code Playgroud)

the*_*oop 5

在 .NET 语言中,对象引用是按值传递的。

那么这是什么意思?从概念上讲,您的代码与此相同,但指针明确:

static void MyMethod(MyClass *obj)
{
    obj->str = "Hello World";
    obj = NULL;
}

static void Main(string[] args)
{
    MyClass *o = new MyClass();
    o->str = "Hello";
    Console.WriteLine(o->str);
    MyMethod(o);

    Console.WriteLine(o->str); // prints "Hello World"
}
Run Code Online (Sandbox Code Playgroud)

传递给的参数MyMethod是指针的值o,指向一个MyClass实例。您可以取消引用指针来设置 的值str,但将实际指针值设置为 null 不会影响调用方法中的变量。

您可以通过执行以下操作来通过引用传递引用:

以下行为的 C# 语言规范是什么。属性的值将被保留,但新实例(空或新对象)不会更新为实际参数。除了更改它指向的对象之外,它基本上具有 ref 的功能。

class Program
{
    class MyClass
    {
        public string str;
    }

    static void MyMethod(ref MyClass obj)
    {
        obj.str = "Hello World";
        obj = null;
    }

    static void Main(string[] args)
    {
        MyClass o = new MyClass();
        o.str = "Hello";
        Console.WriteLine(o.str);
        MyMethod(ref o);

        Console.WriteLine(o.str); // throws NullReferenceException, o is now null
    }
}
Run Code Online (Sandbox Code Playgroud)