如果我从字典中创建列表,并且从列表中的对象更改属性,它会显示在字典中吗? [英] If I make a list from a dictionary and if I change a property from an object of the list, will it show on the dictionary?

查看:56
本文介绍了如果我从字典中创建列表,并且从列表中的对象更改属性,它会显示在字典中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本这样的字典:

private Dictionary<string, TestObject> example = new Dictionary<string, TestObject>() {
            { "object1", new TestObject()},
            { "object2", new TestObject()}
        };

然后我列出一个清单:

internal List<TestObject> exampleList = example.Values.Where(x => x != null).Select(a => a).ToList();

TestObject就是这样

TestObject is something like this

class TestObject{
    string name = "phil";
    public void SetName(string name){
          this.name = name;
    }
}

所以,如果我做这样的事情:

So, if I do something like this:

foreach(TestObject object in exampleList){
    object.SetName("Arthur");
}

该值也会在字典中更改吗?

will the value also change in the dictionary?

推荐答案

TestObject是一个类-因此是引用类型.从字典创建列表时,只需将引用传递给存在于堆中的对象(您可以将引用视为链接).您没有在此处传递对象.甚至字典也不包含对象-它仅包含对对象的引用.您可以有许多指向同一对象的引用.您可以通过任何引用来修改对象.但是对象只是一个.

TestObject is a class - so it is a reference type. When you create the list from the dictionary you just pass references to the objects which live in the heap (you can think about references as links). You are not passing objects here. Even dictionary does not hold objects - it holds only references to objects. You can have many references which point to the same object. And you can modify object via any of references. But the object is only one.

该值也会在字典中更改吗?

will the value also change in the dictionary?

是的,它将.下图说明了原因

Yes, it will. The following picture explains why

如您所见,字典,列表和@object变量在堆栈上-都引用堆上的同一TestObject实例(三个引用).如果您将使用任何引用来修改TestObject名称,则将更新单个TestObject实例.

As you can see, dictionary, list and @object variable on the stack - all reference same TestObject instance on the heap (three references). If you'll use any of the references to modify the TestObject name, that will update single TestObject instance.

请注意,字典Entry是一种结构(值类型),因此其值直接存储在数组中,而不是存储引用.

Note that dictionary Entry is a struct (value type) thus its value is stored in the array directly instead of storing reference.

进一步阅读: .NET类型基础知识

这篇关于如果我从字典中创建列表,并且从列表中的对象更改属性,它会显示在字典中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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