首页 > 解决方案 > 为什么向集合添加值会覆盖以前的项目以及如何简化?

问题描述

基于抽象类,程序将值添加到集合中。问题 1:显示附加值时,它们都被最新的附加值覆盖。作为一个附带问题,添加值似乎很乏味,必须有更好的方法来实现这一点。

浏览其他答案,使用静态类也有类似的问题,但这里不是这种情况。我尝试删除对输出没有影响的“抽象”。

    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

namespace QuoteCoScMe
{
    class Program
    {
        public abstract class Koers
        {
            public string fonds { get; set; }
            public DateTime datum { get; set; }
            public Double koers { get; set; }
        }
        public class Historical : Koers
        {

        }

        private static void Display(Collection<Historical> cs)
        {
            Console.WriteLine();
            foreach (Historical item in cs)
            {
                Console.WriteLine("{0} {1} {2} ", item.fonds, item.datum.ToString(), item.koers);
            }
        }

        static void Main(string[] args)
        {
            Historical xkoers = new Historical() ;
            Collection<Historical> Historicals = new Collection<Historical>();
            xkoers.fonds = "AL1";
            xkoers.datum = DateTime.Parse("2018-05-08");
            xkoers.koers = 310.1;
            Historicals.Add(xkoers);
            xkoers.fonds = "AL2";
            xkoers.datum = DateTime.Parse("2018-06-08");
            xkoers.koers = 320.1;
            Historicals.Add(xkoers);
            xkoers.fonds = "Some other 3";
            xkoers.datum = DateTime.Parse("2019-06-08");
            xkoers.koers = 20.1;
            Historicals.Add(xkoers);
            Display(Historicals);
            /* Question 2: this is a tedious way of adding, i would want to use xkoers.add("AL2", DateTime.Parse("2018-05-08"), 320); */
            /* Question 1: when displaying the historicals for some reason the whole list contains only the latest added item in the list.
               In de VS debugger is shows that all list items have the same values. 

            Output:
                Some other 3 8/06/2019 0:00:00 20,1
                Some other 3 8/06/2019 0:00:00 20,1
                Some other 3 8/06/2019 0:00:00 20,1
                Press any key to continue . . .
             */

        }
    }

}

标签: c#collections

解决方案


你有一个桶:

Historical xkoers = new Historical() ;

然后你把它填满三遍。

每次添加时都需要更新变量:

xkoers = new Historical() ;
xkoers.fonds = "AL1";
xkoers.datum = DateTime.Parse("2018-05-08");
xkoers.koers = 310.1;
Historicals.Add(xkoers);

xkoers = new Historical() ;
xkoers.fonds = "AL2;
xkoers.datum = DateTime.Parse("2018-05-08");
xkoers.koers = 310.1;
Historicals.Add(xkoers);

// etc

至于你的第二个问题,你可以使用构造函数。


推荐阅读