简体   繁体   English

在C#中通过引用传递

[英]Pass by Reference in C#

如何在C#中将参数作为引用传递,以及在调用函数时在定义该特定函数时应如何表示它

As others have said, you should use the ref modifier at both the call site and the method declaration to indicate that you want to use by-reference semantics. 就像其他人所说的,您应该在调用站点和方法声明中都使用ref修饰符,以表明您要使用按引用语义。 However, you should understand how by-value and by-reference semantics interact with the "value type" vs "reference type" model of .NET. 但是,您应该了解按值和按引用语义如何与.NET的“值类型”与“引用类型”模型交互。

I have two articles on this: 我对此有两篇文章:

Here's an example of passing an int by reference: 这是通过引用传递int的示例:

void DoubleInt(ref int x)
{
    x += x;
}

and you would call it like this: 您会这​​样称呼它:

DoubleInt(ref myInt);  

Here's an msdn article about passing parameters. 这是有关传递参数的msdn文章

You can use the ref keyword to pass an object by refence. 您可以使用ref关键字通过引用传递对象。

public void YourFunction(ref SomeObject yourReferenceParameter)
{
    // Do something 
}

When you call it you are also required to give the ref keyword. 调用它时,还需要提供ref关键字。

SomeObject myLocal = new SomeObject();

YourFunction(ref myLocal);

I suggest you take a look at the MSDN documentation about this. 我建议您看看有关此的MSDN文档 It's very clear. 很清楚

Just add ref keyword as prefix to all arguments in the function definition. 只需将ref关键字作为前缀添加到函数定义中的所有参数即可。 Put ref keyword prefix in arguments passed while calling the function. 将ref关键字前缀放在调用函数时传递的参数中。

you can also reference types without need to user ref keyword 您也可以引用类型而无需用户ref关键字
For example you can bass an instance of Class to a method as a parameter without ref keyword 例如,您可以将Class的实例作为参数使用方法,而无需ref关键字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM