开发者

Add operator to third-party type?

开发者 https://www.devze.com 2023-03-22 06:08 出处:网络
I have a third-party library (Mogre), in which is a struct (Vector3)开发者_JAVA百科. I would like to add an overload for the \'+\' operator (no override needed) for this type but am not sure how.

I have a third-party library (Mogre), in which is a struct (Vector3)开发者_JAVA百科. I would like to add an overload for the '+' operator (no override needed) for this type but am not sure how.

I cannot use extension methods as it is an operator I want to extend; the class is not sealed but not partial either, so if I try and define it again with my new operator overload I get conflicts.

Is it possible to extend a type like this? What is the best way to do it?


You cannot add an operator overload to a third-party type -- really any class you don't have the ability to edit. Operator overloads must be defined inside their type they are to operate on (at least one of the args). Since it's not your type, you can't edit it, and structs cannot be extended.

But, even if it was a non-sealed class, you'd have to sub-class, which would ruin the point because they you'd have to use the subclass and not the superclass with the operator, since you can't define the operator overload between the base types...

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

You could do the overload completely between instances of the subclass, but then you'd have to use your new subclass wherever you wanted to do the overload instead of the original superclass, which would look clunky and probably not what you want:

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...
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消