1
public static ListOfPeople operator +( ListOfPeople x, Person y)
    {
        ListOfPeople temp = new ListOfPeople(x);
        if(!temp.PeopleList.Contains(y))
        {
            temp.PeopleList.Add(y);
        }
        temp.SaveNeeded = true;
        return temp;
    }

所以,我从来没有使用过运算符的重载功能,我试图弄清楚如何将我的类 (Person) 中的对象添加到我的 Collection 类 (ListOfPeople) 中。

ListOfPeople 包含一个属性List<Person> PeopleList

我的困难在于如何在此方法中获取一个预先存在的 List 以添加一个新的 Person 。ListOfPeople temp = new ListOfPeople(x);

我在这一行有一个错误,因为我没有接受 ListOfPeople 参数的构造函数。如果我要成功,ListOfPeople temp = new ListOfPeople();那么 Temp 只会调用我的默认构造函数,我只是在其中创建一个新的空列表,并且这也不允许我添加到预先存在的列表中。

我只是不确定如何让“临时”实际引用我预先存在的列表。

4

1 回答 1

1

使用如下:

public static ListOfPeople operator +( ListOfPeople x, Person y)
{
    ListOfPeople temp = x;
    if(!temp.PeopleList.Contains(y))
    {
        temp.PeopleList.Add(y);
    }
    temp.SaveNeeded = true;
    return temp;
}

public static ListOfPeople operator +( Person y, ListOfPeople x)
{
    ListOfPeople temp = x;
    if(!temp.PeopleList.Contains(y))
    {
        temp.PeopleList.Add(y);
    }
    temp.SaveNeeded = true;
    return temp;
}
  • 第一个允许您使用:list = list + person
  • 2nd允许您使用:list = person + list

您可能还想重载+=运算符(非静态),以便您可以使用list += person

编辑

虽然我解决了提到的问题。但是,我同意其他人关于“+”操作数不可变的观点。

以下是对现有代码的更新(假设ListOfPeople.PeopleList is List<Person>):

public static ListOfPeople operator +( ListOfPeople x, Person y)
{
    ListOfPeople temp = new ListOfPeople();
    temp.PeopleList.addRange(x);
    if(!temp.PeopleList.Contains(y))
    {
        temp.PeopleList.Add(y);
    }
    temp.SaveNeeded = true;
    return temp;
}

public static ListOfPeople operator +( Person y, ListOfPeople x)
{
    ListOfPeople temp = new ListOfPeople();
    temp.PeopleList.addRange(x);
    if(!temp.PeopleList.Contains(y))
    {
        temp.PeopleList.Add(y);
    }
    temp.SaveNeeded = true;
    return temp;
}
于 2013-02-17T17:07:06.257 回答