【问题标题】:What is different between Passing by value and Passing by reference using C#使用 C# 按值传递和按引用传递有什么不同
【发布时间】:2009-08-18 10:45:01
【问题描述】:

我很难理解按值传递和按引用传递之间的区别。有人可以提供一个 C# 示例来说明差异吗?

【问题讨论】:

  • 那是 sort of 重复的,但这特别要求 C# 示例 - 而在引用的问题中根本没有 C# 示例。当然,有很多很好的一般性讨论,但我认为也有针对特定语言的讨论并没有什么坏处。
  • @Jon Skeet:将 C# 语法的答案粘贴到现有问题中不是正确的解决方案吗?大概是在编辑一个现有的答案。

标签: c#


【解决方案1】:

一般情况下,请阅读my article about parameter passing

基本思路是:

如果参数是通过引用传递的,那么方法内参数值的变化也会影响参数。

微妙之处在于,如果参数是引用类型,那么做:

someParameter.SomeProperty = "New Value";

没有改变参数的值。参数只是一个引用,上面并没有改变参数所指的内容,只是对象内部的数据。这是真正更改参数值的示例:

someParameter = new ParameterType();

现在举例:

简单示例:通过 ref 或按值传递 int

class Test
{
    static void Main()
    {
        int i = 10;
        PassByRef(ref i);
        // Now i is 20
        PassByValue(i);
        // i is *still* 20
    }

    static void PassByRef(ref int x)
    {
        x = 20;
    }

    static void PassByValue(int x)
    {
        x = 50;
    }
}

更复杂的例子:使用引用类型

class Test
{
    static void Main()
    {
        StringBuilder builder = new StringBuilder();
        PassByRef(ref builder);
        // builder now refers to the StringBuilder
        // constructed in PassByRef

        PassByValueChangeContents(builder);
        // builder still refers to the same StringBuilder
        // but then contents has changed

        PassByValueChangeParameter(builder);
        // builder still refers to the same StringBuilder,
        // not the new one created in PassByValueChangeParameter
    }

    static void PassByRef(ref StringBuilder x)
    {
        x = new StringBuilder("Created in PassByRef");
    }

    static void PassByValueChangeContents(StringBuilder x)
    {
        x.Append(" ... and changed in PassByValueChangeContents");
    }

    static void PassByValueChangeParameter(StringBuilder x)
    {
        // This new object won't be "seen" by the caller
        x = new StringBuilder("Created in PassByValueChangeParameter");
    }
}

【讨论】:

    【解决方案2】:

    按值传递意味着传递参数的副本。对该副本的更改不会更改原件。

    通过引用传递意味着对原始的引用被传递并且对引用的更改会影响原始。

    这不是 C# 特有的,它存在于许多语言中。

    【讨论】:

      【解决方案3】:

      摘要是:

      当您希望函数/方法修改您的变量时,使用通过引用传递。

      在你不这样做时按值传递。

      【讨论】:

        猜你喜欢
        • 2012-07-29
        • 1970-01-01
        • 2023-03-07
        • 2014-08-23
        • 2015-05-23
        • 2023-03-02
        • 2011-05-08
        • 2012-05-05
        • 1970-01-01
        相关资源
        最近更新 更多