gpt4 book ai didi

c#对象按引用传递还是按值传递

转载 作者:太空狗 更新时间:2023-10-30 00:19:34 24 4
gpt4 key购买 nike

以下代码的输出让我感到惊讶。我认为“a”应该包含对新创建对象的引用。谁能解释为什么结果不是 2?

class Program
{
static void Main(string[] args)
{
aclass a = new aclass();
Process(a);
Console.WriteLine(a.number);

Console.ReadLine();
}

static void Process(aclass a)
{
aclass temp = new aclass();
temp.number++;
//Console.WriteLine(temp.number);

a = temp;
a.number++;
//Console.WriteLine(a.number);
}

}

class aclass
{
public int number = 0;
}

编辑:这是一道面试题。我刚刚意识到我长期以来一直误解了这个概念。参数 a 与原始 a 不同,尽管它们引用相同的地址。

最佳答案

您并没有更改实际的原始引用,您只是更改了参数中保存的引用,它微妙地不同,更改不会持久返回给调用者。您可以使用 outref 更改此行为。

在这种情况下,您特别希望使用 ref,因为您还传递了一个引用。

尝试:

class Program
{
static void Main(string[] args)
{
aclass a = new aclass();
Process(ref a);
Console.WriteLine(a.number);

Console.ReadLine();
}

static void Process(ref aclass a)
{
aclass temp = new aclass();
temp.number++;
//Console.WriteLine(temp.number);

a = temp;
a.number++;
//Console.WriteLine(a.number);
}

}

请记住,您正在使用 a = temp 分配一个全新的引用。如果您只想更新您最初传入的现有类,那么您可以这样做:

a.number = temp.number;
a.number++;

这将否定对 ref 的需求。

您可以在 MSDN 上阅读更多内容:

Passing Reference Type Parameters

ref Keyword

out Keyword

关于c#对象按引用传递还是按值传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19113979/

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