【问题标题】:Add an Object with a List of Objects to a List [closed]将带有对象列表的对象添加到列表中[关闭]
【发布时间】:2014-08-16 19:42:44
【问题描述】:

我在尝试将对象添加到列表时遇到了一点问题。我在 c# 中工作。

带有对象列表的对象:

public class Person 
{
    public string Title { get; set; }
    public List<Names> FullNames { get; set; }
}

名称 对象

public class Names
{
    string First { get; set; }
    string Middle { get; set; }
    string Last { get; set; }

    public Names(string First, string Middle, string Last)
    {
        this.First = First;
        this.Middle = Middle;
        this.Last = Last;
    }
}

问题领域:

在主窗口中,我创建了一个 Person 类型的 Observable 集合。您如何正确实现添加 FullNames 列表?我根本无法让它工作。

public partial class MainWindow : Window
{

    public ObservableCollection<Person> people { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        people.Add(new Person() { Title = "President", FullNames = new Names(First = "George", Middle = "K", Last = "Will")}); //problem area
    }
}

【问题讨论】:

  • 您尝试将TodoItem 添加到ObservableCollection&lt;Person&gt; - 这意味着什么?
  • “TodoItem”不是我的意思,抱歉——我只是将“TodoItem”编辑为“Person”。

标签: c# wpf object observablecollection


【解决方案1】:

好的,有几件事。

  1. 你有一个NullReferenceException 等待发生。 people 被初始化为 null,你直接添加到它而不给它一个实例。
  2. 您有一个包含Person 对象的集合,并且您正在向其中添加TodoItem。其中之一是错误的。
  3. 您真正的问题,您需要在FullNames 属性上使用List 初始化程序,因为它看起来就像您正在尝试设置List&lt;T&gt; = T,这不会任何意义。
  4. 您正在使用= 调用Names 的构造函数,这是错误的语法。您想省略参数名称。正如@RohitVats 指出的那样,您也可以使用: 来指定,但在这里您真的不想这样做。构造函数实际上只是一个方法调用,因此与任何其他函数(在大多数情况下)相同的语法规则适用于它们。

为了解决这些问题,您的代码应如下所示:

public MainWindow()
{
    InitializeComponent();

    people = new ObservableCollection<Person>();
    people.Add(new Person()
               {
                   Title = "President",
                   FullNames = new List<Names>()
                               {
                                   new Names("George", "K", "Will")
                               }
               });
}

为了确保您理解这里发生了什么,这与写作相同:

public MainWindow()
{
    InitializeComponent();

    people = new ObservableCollection<Person>();
    Person toAdd = new Person();
    toAdd.Title = "President";
    toAdd.FullNames = new List<Names>();
    toAdd.FullNames.Add(new Names("George", "K", "Will"));
    people.Add(toAdd);
}

这不是一个错误,但你真的应该考虑将你的 Names 类型名称调整为单数,即使只是 FullName,因为它现在很难阅读。我知道你从哪里来,因为实际上有多个名字(名字、中间名和姓氏),但这仍然令人困惑。

【讨论】:

  • 构造函数参数中的语法不正确。这不会编译。
【解决方案2】:
  1. 首先初始化人员列表。
  2. 您只能在集合中添加 Person 对象。
  3. 名称应初始化为列表。
  4. 带参数的构造函数调用不正确。

而不是First = "George",它应该是First : "George",或者如果以与定义中相同的顺序传递,则完全省略参数名称。


这应该可行:

people.Add(new Person() { Title = "President",
                          FullNames = new List<Names>()
                              { new Names("George", "K", "Will") } });

【讨论】:

  • 这行得通。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 2018-07-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多