c#运算符重载使用情况

时间:2013-02-17 16:58:08

标签: c# overloading operator-keyword

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只会调用我的默认构造函数,我只需创建一个新的空列表,并且不允许我添加到预先存在的列表中。

我只是不确定如何实际参考我之前存在的列表。

1 个答案:

答案 0 :(得分: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;
}
  • 1st允许您使用: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;
}