使用C#什么是价值与传承之间传递不同的参照 [英] what is different between Passing by value and Passing by reference using C#

查看:105
本文介绍了使用C#什么是价值与传承之间传递不同的参照的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:

什么&rsquo的; S按引用传递参数之间的区别与按值传递

我很难理解按值传递之间的差异,通过引用传递。 ?有人可以提供说明差异C#示例

I have difficulty understanding the difference between passing by value and passing by reference. Can someone provide a C# example illustrating the difference?

推荐答案

在一般情况下,读出的我的有关参数传递文章

In general, read my article about parameter passing.

其基本思想是:

如果参数按引用传递,然后改到方法中的参数值将影响参数以及

微妙的是,如果该参数是引用类型,那么这样做的:

The subtle part is that if the parameter is a reference type, then doing:

someParameter.SomeProperty = "New Value";

不是的改变参数的值。的参数仅仅是一个参考,和上述的不改变参数是指,刚刚在对象内的数据的内容。下面是一个例子的真正的改变参数的值:

isn't changing the value of the parameter. The parameter is just a reference, and the above doesn't change what the parameter refers to, just the data within the object. Here's an example of genuinely changing the parameter's 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");
    }
}

这篇关于使用C#什么是价值与传承之间传递不同的参照的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆