我有一个第三方库(Mogre),其中有一个结构体(Vector3)。我想为此类型添加“+”运算符的重载(无需覆盖),但不确定如何操作。
我无法使用扩展方法,因为它是我想要扩展的运算符;该类不是密封
,但也不是部分
,因此,如果我尝试使用新的运算符重载再次定义它,则会发生冲突。
是否可以扩展这样的类型?最好的方法是什么?
最佳答案
您不能将运算符重载添加到第三方类型——实际上是您无法编辑的任何类。运算符重载必须在其要操作的类型(至少其中一个参数)内定义。由于它不是您的类型,因此您无法编辑它,并且无法扩展 struct
。
但是,即使它是一个非密封类
,您也必须进行子类化,这会破坏这一点,因为您必须使用子类而不是父类(super 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...
}
}
您可以在子类的实例之间完全进行重载,但是您必须在任何想要进行重载的地方使用新的子类,而不是原始的父类(super class),这看起来很笨重,而且可能不是您想要的:
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...
}
}
关于c# - 将运算符添加到第三方类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6767734/