【问题标题】:Add operator to third-party type?将运营商添加到第三方类型?
【发布时间】:2011-07-21 04:06:44
【问题描述】:

我有一个第三方库 (Mogre),其中是一个结构 (Vector3)。我想为这种类型的“+”运算符添加一个重载(不需要覆盖),但不确定如何。

我不能使用扩展方法,因为它是我想要扩展的运算符;该类不是sealed,但也不是partial,所以如果我尝试使用新的运算符重载再次定义它,我会遇到冲突。

是否可以扩展这样的类型?最好的方法是什么?

【问题讨论】:

  • 尝试扩展此类并将其作为自定义类的基类,在该类中定义运算符重载
  • 但是他必须在子类之间使用运算符重载,而不是在基类中使用。
  • 你说 Vector3 是一个结构体,然后又说这个类不是密封的或部分的……它是一个结构体还是一个类?

标签: c# types operator-overloading


【解决方案1】:

您不能将运算符重载添加到第三方类型——实际上是您无法编辑的任何类。运算符重载必须在它们要操作的类型中定义(至少一个参数)。因为不是你的类型,所以不能编辑,structs 也不能扩展。

但是,即使它是非sealed class,你也必须子类,这会破坏这一点,因为他们必须使用子类而不是超类和运算符,因为你无法定义基类型之间的运算符重载...

public class A
{
    public int X { get; set; }
}

public class B : A
{
    public static A operator + (A first, A second)
    {
        // this won't compile because either first or second must be type B...
    }
}

您可以在子类的实例之间完全进行重载,但是您必须在要进行重载的任何地方使用新的子类,而不是原始超类,这看起来很笨重,可能不是您想要的:

public class A
{
    public int X { get; set; }
}

public class B : A
{
    public static B operator + (B first, B second)
    {
        // You could do this, but then you'd have to use the subclass B everywhere you wanted to
        // do this instead of the original class A, which may be undesirable...
    }
}

【讨论】:

  • 感谢您的回答。 (抱歉,我之前从未尝试将这些修饰符与 struct def. 一起使用,并且不知道它们在结构中是不允许的)为此,任何可读性的提高都将通过使用子类来抵消你所说的一半时间,但是对于更复杂的扩展当然值得。
猜你喜欢
  • 2015-03-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-09
  • 1970-01-01
  • 2018-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多