我有一个类,它的构造函数在下面
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.
更多推荐
发布评论