通过引用传递引用 [英] Passing a reference by reference

查看:61
本文介绍了通过引用传递引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过引用传递引用对象有什么用.常规用法如下:

How could it be any useful to pass a reference object by reference. The regular usage is as the following:

public static void main()
{
    Student st = new Student();
    st.FirstName = "Marc";
    PutLastName(st);
    Console.WriteLLine(st.FirstName + " " + st.LastName);
}

public static PutLastName(Student student)
{
    student.LastName = "Anthony";
}

为什么有人会写以下内容,它做同样的事情并且打印:Marc Anthony":

Why would anybody write the following, which does the same thing and does print: "Marc Anthony":

public static void main()
{
    Student st = new Student();
    st.FirstName = "Marc";
    PutLastName(ref st);
    Console.WriteLLine(st.FirstName + " " + st.LastName);
}

public static PutLastName(ref Student student)
{
    student.LastName = "Anthony";
}

推荐答案

它并没有做同样的事情......在幕后.

It doesn't do the same thing.. under the hood.

在功能上,它的工作原理是一样的,是的.虽然在幕后......使用 ref 时会传递引用本身.没有ref,引用值被复制.

Functionally, it works the same, yes. Under the hood though.. the reference itself is being passed when using ref. Without ref, the reference value is copied.

将引用视为内存指针.student 的值为 1134...一个内存地址.当您不使用 ref 时,1134 将应用于新的引用.. 指向相同的内存地址.

Think of references as memory pointers. student has the value 1134.. a memory address. When you don't use ref, 1134 is applied to a new reference.. pointing at the same memory address.

当您意识到上述情况时,使用 ref 可能会产生危险的后果.例如,考虑这个:

Using ref can have dangerous consequences when you realise the above. For example, consider this:

public static void PutLastName(Student student)
{
    student = new Student();
    student.LastName = "Whitehead";
}

// .. calling code ..
Student st = new Student();
st.FirstName = "Marc";
st.LastName = "Anthony";
PutLastName(st);
Console.WriteLLine(st.FirstName + " " + st.LastName); // "Marc Anthony"

然而,使用 ref:

public static void PutLastName(ref Student student)
{
    student = new Student();
    student.FirstName = "Simon";
    student.LastName = "Whitehead";
}

// .. calling code ..
Student st = new Student();
st.FirstName = "Marc";
st.LastName = "Anthony";
PutLastName(ref st);
Console.WriteLLine(st.FirstName + " " + st.LastName); // "Simon Whitehead"

使用 ref 物理改变了引用.没有它......你只是告诉一个不同的引用指向其他地方(一旦函数退出,它就无效).所以,当使用 ref 时,你给了被调用者物理改变引用本身的能力......而不仅仅是它指向的内存.

Using ref physically changed the reference. Without it.. you're just telling a different reference to point somewhere else (which is void once the function steps out). So, when using ref, you're giving the callee the ability to physically change the reference itself.. not just the memory it points at.

这篇关于通过引用传递引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆