【问题标题】:Overriding an operator overloading method重写运算符重载方法
【发布时间】:2016-12-14 02:38:54
【问题描述】:

我有一个父类和另一个继承父类的子类。

我在 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...
}

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

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);
  }
}

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

【问题讨论】:

  • 你是否尝试过使用父类的类型来启动一个子类对象比如“Parent A = new Child();”
  • 即使我使用Parent发起,如何将(Parent + Parent)转换回Child?
  • 旁注:当您遇到此问题时,这可能意味着没有人能够理解 Parent + Child 的期望,因此将无法阅读代码。此时,使用构建器方法或其他方法可能是更好的选择。

标签: c# class operator-overloading overriding


【解决方案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.
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    相关资源
    最近更新 更多