c# - "ref"使用实例

标签 c# 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/

相关文章:

c# - Ref 参数返回未知大小的数组。如何处理?

c# - 向 WPF 窗体添加和显示 FixedDocument

c# - 将文件内容从 php curl(使用 post)发送到 c# webapi

c# - MethodImpl(No Optimization) 在这个方法上,它做了什么?而且真的有必要吗?

c# - 是否可以采取变通方法通过 ref 传递属性?加上路过引用事件

C# 为什么我不能通过 ref 传递 "base"接口(interface)?

c# - 引用的项目中抛出异常?

c# - DrawRectangle 中的边框

javascript - 如何在 Vue3 中使用 ref 访问父组件中的子组件方法?

javascript - 使用 ref react Canvas ,省略调用 ref.current 和 ctx?