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

查看:34
本文介绍了在 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 关键字吗?

Should I use the ref keyword for that?

我对在 C# 中在哪里使用 refout 关键字感到有些困惑,因为所有都是在堆上动态分配的,并且我们实际上在大多数操作中使用指针.
当然,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天全站免登陆