gpt4 book ai didi

c# - 传递引用和引用

转载 作者:太空宇宙 更新时间:2023-11-03 18:30:18 25 4
gpt4 key购买 nike

<分区>

我已经阅读了一些 MSDN 上的教程,以了解 C# 中的按引用传递、refout,我遇到了以下代码示例:

using System;

class TheClass
{
public int x;
}

struct TheStruct
{
public int x;
}

class TestClass
{
public static void structtaker(TheStruct s)
{
s.x = 5;
}
public static void classtaker(TheClass c)
{
c.x = 5;
}
public static void Main()
{
TheStruct a = new TheStruct();
TheClass b = new TheClass();
a.x = 1;
b.x = 1;
structtaker(a);
classtaker(b);
Console.WriteLine("a.x = {0}", a.x); //prints 1
Console.WriteLine("b.x = {0}", b.x); //prints 5
}
}

教程中对此的注释:

This example shows that when a struct is passed to a method, a copy of the struct is passed, but when a class instance is passed, a reference is passed.

我完全理解,但我的问题是,如果在 C# 中将引用传递给参数,为什么他们需要 ref,如下例所示:

void tearDown(ref myClass a)
{
a = null;
}

MyClass b = new MyClass();
this.tearDown(ref b);
assert(b == null);
//b is null

???我认为 C# 在 C 中是相同的 - 按值传递。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com