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

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

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

基本思路是:

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

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

someParameter.SomeProperty = "New Value"; 

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

 someParameter = new ParameterType(); 

现在举个例子:

简单示例:通过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; } } 

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

 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#特有的,它存在于多种语言中。

摘要是:

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

当你不这样做时,按价值传递。