1
case Choices.ADD_PERSON:
                    Console.WriteLine("enter info for person to add.");
                    InfoForPerson();
                    PersonList Z = x + p;
                    break;

case Choices.REMOVE_PERSON:
                    Console.WriteLine("enter info for person to remove: ");
                    InfoForPerson();
                    Z = x - p;
                    break;

以上是从菜单中选择选项时发生的两件事。因为Choices.ADD_PERSON结果符合预期,又加了一个人。但是,我假设 + & - 会以完全相同的方式起作用,只是相反,但它并没有发生。

public static PersonList operator -(PersonList x, Person y)
    {
        PersonList temp = x;
        if (temp._Plist.Contains(y))
        {
            temp._Plist.Remove(y);
        }
        return temp; }

以上是我对减法运算符的定义。下面是我用来允许用户选择要添加/减去的人的代码。

public static void InfoForPerson()
    {
        Console.Write("Enter your name: ");
        string name = Console.ReadLine();
        string phone = ValidPhone();
        string email = ValidEmail();
        p = new Person(name, phone, email);

它适用于加法,而不是减法。我看了 p 并且它保存的数据很好,但它与列表中已经存在的项目不匹配。

4

2 回答 2

3

正如@sapi 和@TheEvilPenguin 已经指出的那样,这种类型的运算符重载是不受欢迎的,原因有很多。然而,这并不能回答你的问题。

如果没有关于您pZ = x - p声明中的来源的更多信息,我会怀疑您的问题是该p元素不存在于列表中。

请记住,Contains并且Remove仅对列表中对象的特定实例有效。

List<Tuple<int, int>> collection = new List<Tuple<int, int>>();
collection.Add(new Tuple<int, int>(1, 1));
if (collection.Contains(new Tuple<int, int>(1, 1))
{
    Console.WriteLine("This will NEVER happen.");
}
collection.Remove(new Tuple<int, int>(1, 1);
Console.WriteLine("{0}", collection.Count); // => 1

如果您想测试是否存在与测试值具有相同属性的类型的任何实例,则不Contains会这样做。

另外一点,-操作员不应该(有人会说必须不)修改左边的操作数。您应该返回一个包含过滤项目的新列表,因为这是A - B.

于 2013-02-19T02:34:54.670 回答
2

无论您使用哪种类型的列表(或集合),都_Plist需要支持匹配Person为“值”(如果引用则默认)。您可以将自定义比较器传递给包含函数或实现EqualsGetHashCode继续Person比较所有属性。

注意:正如大家所说,在非数学相关的课程中使用 +/- 会导致代码不直观。即你已经有奇怪的行为 - 如果元素不存在,-将什么也不做。数字永远不会发生这种情况:whatever -2从不等于whatever

于 2013-02-19T02:33:31.860 回答