重复列表< T> .Add(T项目)项目 [英] Duplicate List<T>.Add(T item) Items

查看:64
本文介绍了重复列表< T> .Add(T项目)项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么aFooList包含最后一个项目的五个副本,而不是我插入的五个项目?

Why does aFooList contain five copies of the last item, instead of the five items I inserted?

预期输出:01234

实际输出:44444

using System;
using System.Collections.Generic;

namespace myTestConsole {
    public class foo {
        public int bar;
    }

    class Program {
        static void Main(string[] args) {
            foo aFoo = new foo(); // Make a foo
            List<foo> aFooList = new List<foo>(); // Make a foo list

            for (int i = 0; i<5; i++) { 
                aFoo.bar = i;
                aFooList.Add(aFoo);
            }

            for (int i = 0; i<5; i++) {
                Console.Write(aFooList[i].bar);
            }
        }
    }
}

推荐答案

您已添加同一项aFoo 5次.修改引用类型对象的内容时,您不会创建新副本,而是修改了同一对象.

You have added the same item, aFoo, 5 times. When you modify contents of a reference-type object you don't create new copies, you modify the same object.

这篇关于重复列表&lt; T&gt; .Add(T项目)项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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