指向c#中字典的指针(Pointer to a dictionary in c#)

编程入门 行业动态 更新时间:2024-10-28 03:21:49
指向c#中字典<>的指针(Pointer to a dictionary<> in c#)

我有一个类,它的构造函数在下面

public GroupsForm(ref Dictionary<string, List<string>> groupsList)

我想在其他函数中使用groupsList,所以我在类中声明了一个私有成员:

private Dictionary<string, List<string>> _groupsList;

但问题是当我做_groupsList = groupsList; 它生成groupsList的副本,对groupsList更改不会更改groupsList ,因为我认为默认情况下会进行深层复制。 我想要的是它应该指向该列表。

在C ++中,这可以通过指针轻松完成,但任何人都可以告诉我如何在C#中执行此操作?


Ahmed已发布此图片 :

I have a class, which its constructor is below

public GroupsForm(ref Dictionary<string, List<string>> groupsList)

I want to use the groupsList in other functions as well so I declared a private member in the class:

private Dictionary<string, List<string>> _groupsList;

But the problem is when I do _groupsList = groupsList; it makes a copy of the groupsList and changes made to _groupsList doesn't change groupsList, as I think it makes a deep copy by default. What I want is that it should point to that list.

In C++, this can easily be done via pointers, but can anyone tell me how can I do this in C#?


Ahmed has posted this image:

最满意答案

在你的InitGroups方法中,你有一个_groupsList的赋值语句 - 这是包含3个项目的新列表。 您可以更改InitGroups以执行以下操作:

var newGroups = (Dictionary<string, List<string>>)ser.ReadObject(reader,true); foreach(var kvp in newGroups) { _groupsList.Add(kvp.Key,kvp.Value); }

然后你仍然会使用相同的Dictionary对象。

In your InitGroups method, you've got an assignment statement to _groupsList - it's this new list that contains 3 items. You could change InitGroups to do something like:

var newGroups = (Dictionary<string, List<string>>)ser.ReadObject(reader,true); foreach(var kvp in newGroups) { _groupsList.Add(kvp.Key,kvp.Value); }

And then you'll still be working with the same Dictionary object.

更多推荐

本文发布于:2023-07-30 06:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336685.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   字典   dictionary   Pointer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!