c#运算符重载用法
本文关键字:用法 重载 运算符 | 更新日期: 2023-09-27 17:59:50
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
;
我的困难在于如何在该方法中获取预先存在的列表,以将新的Person添加到.ListOfPeople temp = new ListOfPeople(x);
这一行有一个错误,因为我没有接受ListOfPeople参数的构造函数。如果我让它成为ListOfPeople temp = new ListOfPeople();
,那么Temp只会调用我的默认构造函数,我只需在其中创建一个新的空列表,这也不允许我添加到预先存在的列表中。
我只是不确定我是如何得到"temp"来实际引用我预先存在的列表的。
使用如下:
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
- 第2个允许您使用:
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;
}