<分区>
我正在努力如何在实际应用程序中使用“ref”(通过引用传递参数)。我想要一个简单且主要有意义的例子。到目前为止,我发现的所有内容都可以通过向方法添加返回类型轻松重做。 有人知道吗? 谢谢!
<分区>
我正在努力如何在实际应用程序中使用“ref”(通过引用传递参数)。我想要一个简单且主要有意义的例子。到目前为止,我发现的所有内容都可以通过向方法添加返回类型轻松重做。 有人知道吗? 谢谢!
最佳答案
我想到的最好的例子是交换两个变量值的函数:
static void Swap<T>(ref T el1, ref T el2)
{
var mem = el1;
el1 = el2;
el2 = mem;
}
用法:
static void Main(string[] args)
{
string a = "Hello";
string b = "Hi";
Swap(ref a, ref b);
// now a = "Hi" b = "Hello"
// it works also with array values:
int[] arr = new[] { 1, 2, 3 };
Swap(ref arr[0], ref arr[2]);
// now arr = {3,2,1}
}
像这样的函数,没有 ref
关键字是无法完成的。
关于c# - "ref"使用实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4646159/