【问题标题】:Issue adding to a List of a custom class type添加到自定义类类型列表的问题
【发布时间】:2019-02-03 04:36:12
【问题描述】:

对于某人来说,这很可能是一个非常基本的问题,但我无法理解它。基本上我有一个列表的自定义类:

public class CorrectiveMaintResults
{
    public string Comment { get; set; }
    public string Cleared { get; set; }
}

我最终将它存储在一个数据库中,我在每个项目之间放置了一个换行符,用于注释和清除。然后我将其检索并放回表中。为了实现这一点,我创建了两个私人列表,它们从数据库中获取评论和清除数据。

我要做的是创建一个 for 或 foreach 循环,以将两个私有列表添加回我的自定义列表 (correctiveMainResults)。这就是我正在尝试的:

for (int i = 0; i < correctiveMainComment.Count; i++)
{
    maintResults.Comment = correctiveMainComment[i];
    maintResults.Cleared = correctiveMainCleared[i];

    FormResults.correctiveMainResults.Add(maintResults);
}

mainResults 是我对类的初始化:

CorrectiveMaintResults maintResults = new CorrectiveMaintResults();

我遇到的问题是,当结果被添加到 FormResults.correctiveMainResults 时,它似乎只出现在每个列表的最后一个索引中并且只是重复它。

希望有人可以帮助或理解我的意思。很难在没有实际看到应用程序运行的情况下进行解释。

【问题讨论】:

  • 您应该在循环中创建一个新的CorrectiveMaintResults,而不是覆盖同一个对象的属性。只需在循环内移动初始化行。
  • 类似于@linuxrocks。感谢您的帮助
  • 说明:你的 for 循环所做的是,将同一个对象引用多次添加到列表中。这意味着列表中的每个条目都指向同一个对象。在你的最后一个循环之后,它保存了你的帮助列表的最后一个索引的值(因此是重复的)。
  • @croxy 好的,感谢您的解释。赞赏!

标签: c# ios sqlite xamarin.ios


【解决方案1】:

您只在循环之外创建了一个对象。试试这样的:

for (int i = 0; i < correctiveMainComment.Count; i++) {
    CorrectiveMaintResults maintResults = new CorrectiveMaintResults();
    maintResults.Comment = correctiveMainComment[i];
    maintResults.Cleared = correctiveMainCleared[i];

    FormResults.correctiveMainResults.Add(maintResults);
}

【讨论】:

  • 谢谢,效果很好!一旦它允许我会接受答案
猜你喜欢
  • 1970-01-01
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-04
  • 1970-01-01
  • 1970-01-01
  • 2017-12-04
相关资源
最近更新 更多