我有一个第三方库(Mogre),其中是一个struct(Vector3)。我想为这个类型的'+'运算符添加一个重载(不需要覆盖),但我不确定如何。
我不能使用扩展方法,因为它是我想要扩展的运算符;该类不是sealed
而是partial
,所以如果我尝试使用我的新运算符重载再次定义它,我会遇到冲突。
是否可以扩展这样的类型?最好的方法是什么?
答案 0 :(得分:3)
您无法将操作员重载添加到第三方类型 - 实际上任何您无法编辑的类。必须在它们要操作的类型(至少一个args)内定义操作符重载。由于它不是您的类型,因此您无法对其进行编辑,并且struct
无法扩展。
但是,即使它是非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...
}
}