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)