覆盖运算符重载方法

时间:2016-12-14 02:38:55

标签: c# class operator-overloading override

我有一个类Parent和另一个继承Parent的类。

我在Parent中有一个运算符重载方法,我想让它也可以在Child上运行。但是我不知道该怎么做。

public class Parent
{
  public int age;
  public static Parent operator + (Parent a, Parent b)
  {
    Parent c = new Parent();
    c.age = a.age + b.age;
    return c;
  }
}

public class Child : Parent
{
   //other fields...
}

我能想到的唯一方法是将完全相同的方法和逻辑复制到child。但是我认为这不是一个好方法,因为代码是多余的:(特别是当代码很长时)

public class Child : Parent
{
  public static Child operator + (Child a, Child b)
  {
    Child c = new Child();
    c.age = a.age + b.age;
    return c;
  }
}

我尝试进行转换,但在运行时失败:

public class Child : Parent
{
  public static Child operator + (Child a, Child b)
  {
    return (Child)((Parent)a + (Parent)b);
  }
}

有没有更好的方法来实现这一目标?非常感谢你。

1 个答案:

答案 0 :(得分:1)

最终你必须创建Child对象,但是你可以将逻辑移动到受保护的方法中。

public class Parent
{
  public int age;
  public static Parent operator + (Parent a, Parent b)
  {
    Parent c = new Parent();
    AddImplementation(a, b, c);
    return c;
  }

  protected static void AddImplementation(Parent a, Parent b, Parent sum)
  {
    sum.age = a.age + b.age;
  }
}

public class Child : Parent
{
  public static Child operator + (Child a, Child b)
  {
    Child c = new Child();
    AddImplementation(a, b, c);
    return c;
  }
}

或者另一种选择是将逻辑移动到运算符调用的受保护构造函数

public class Parent
{
    public int age;
    public static Parent operator +(Parent a, Parent b)
    {
        return new Parent(a, b);
    }

    protected Parent(Parent a, Parent b)
    {
      this.age = a.age + b.age;
    }
}

public class Child : Parent
{
    public static Child operator +(Child a, Child b)
    {
        return new Child(a, b);
    }

    protected Child(Child a, Child b) : base(a,b)
    {
        // anything you need to do for adding children on top of the parent code.
    }
}
相关问题