在类C#中使用ref [英] using ref with class C#

查看:209
本文介绍了在类C#中使用ref的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想给我正在上课的某个链接列表.我希望该类写入该列表(例如,通过.addLast()).

I want to give a certain linked list to a class I am making. I want the class to write into that list (eg by .addLast()).

我该使用ref关键字吗?

对于在C#中使用refout关键字的地方,我有些困惑,因为所有 classes 都是在堆上动态分配的,而实际上我们对大多数操作使用了指针. > 当然,outref关键字对于基元和结构有意义.

I am somewhat puzzled on where to use the ref and out keywords in C#, as all classes are allocated dynamically on the heap and we actually use pointers for most operations.
Of course, out and ref keywords make sense for primitives and structs.

此外,如果我不直接发送列表,而是发送包含列表的类? (必须为internal),我是否仍需要使用ref?或者,如果我在函数之间传递它,例如:

Also, if I don't send the list directly, but send a class containing the list? (it's internal and needed), do I still need to use ref? or if I pass it between functions, ex:

void A(ref LinkedList<int> list){
    B(list);
}

void B(ref LinkedList<int> list){
    _myList = list;
}

推荐答案

对于您正在做的事情,您无需使用ref.如果确实使用ref传递了列表,则将允许调用者更改要引用的列表,而不仅仅是更改列表的内容.

For what you're doing you don't need to use ref. If you did pass the list using ref, you would be allowing the caller to change which list you're referencing, rather than just changing the contents of the list.

这篇关于在类C#中使用ref的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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