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

标签 c# object-reference

以下代码的输出让我感到惊讶。我认为“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/

相关文章:

java - 类作为变量类型

java - 字符串连接时 Java 字符串池如何工作?

c# - RSACryptoServiceProvider 不产生一致的输出

c# - 通用对象缓存

c# - Gridview 在编辑前检查约束

c# - List<Task> - 使用 C# Entity Framework 的 UPSERT 数据库记录

java - EditText 值未反射(reflect)出来,它显示以前的值,但是当您打印 EditText 的 getText 时,它显示正确的值

c# - 在进程开始之前对命令行参数执行什么处理/验证?

c# - 将非映射属性添加到实体 EF5

javascript - array.forEach 的 thisArg 没有按预期引用