使用C#传递值和通过引用传递之间有什么不同

7 c#

我很难理解传递值和传递参考之间的区别.有人可以提供说明差异的C#示例吗?

Jon*_*eet 17

一般来说,阅读我关于参数传递的文章.

基本思路是:

如果参数是通过引用传递的,那么对方法中参数值的更改也会影响参数.

细微的部分是,如果参数是引用类型,那么执行:

someParameter.SomeProperty = "New Value";
Run Code Online (Sandbox Code Playgroud)

不会更改参数的值.该参数只是一个引用,上面的内容不会改变参数引用的内容,只会更改对象中的数据.以下是真正更改参数值的示例:

someParameter = new ParameterType();
Run Code Online (Sandbox Code Playgroud)

现在举个例子:

简单示例:通过ref或value传递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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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");
    }
}
Run Code Online (Sandbox Code Playgroud)


pax*_*blo 5

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

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

这不是C#特有的,它以多种语言存在.