c# - 为什么向集合添加值会覆盖以前的项目以及如何简化?
问题描述
基于抽象类,程序将值添加到集合中。问题 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 . . .
*/
}
}
}
解决方案
你有一个桶:
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
至于你的第二个问题,你可以使用构造函数。
推荐阅读
- c# - Linq to XML - 读取多个属性的值
- python-3.x - ABAQUS使用Python保存打开的excel“Book1”
- ssh - Ansible 使用密码配置跳转主机
- c - C - 将二维数组传递给函数仅打印第一行
- node.js - 使用 Express 的 Node.js 3rd 方 API 调用
- css - 如何使 flexbox 列忽略子 div 的子项的高度
- mysql - Laravel - 通过 json_extract 和 eloquent select 获取一个简单数组的值
- c - 将字符串放入结构中会引发在 C 中转储的分段错误核心
- javascript - 频道名称中的 Discord.js memberCount 按角色(node.js)
- c - 如何以返回字符串的方式更改此代码