开发者

Why can't I overload the * operator to multiply rectangles with 2D vectors?

开发者 https://www.devze.com 2023-03-16 18:44 出处:网络
I was trying to overload the multiplication operator for convenience of scaling 2D sprites, but it seems like one of the operands has to be of a containing type. This is a pity cause I don\'t find my

I was trying to overload the multiplication operator for convenience of scaling 2D sprites, but it seems like one of the operands has to be of a containing type. This is a pity cause I don't find my solution illogical. Also, I found out that such operator overloads should b开发者_如何转开发e declared within the class declaration of one of the operands. So, do I have to create my own custom SuperRectangle class or there are some workarounds?

public static Rectangle operator * (Rectangle rect, Vector2 scale)
{
    return new Rectangle(rect.X, rect.Y, (int)(rect.Width * scale.X), (int)(rect.Height * scale.Y));
}


You can overload * if one or more of the types is user-defined and the overload definition is contained within one of the types involved. If the types involved are built-in and/or you do not control the source code, you will not be able to define your own overload. (See: Sections 7.3 and 7.3.2 of the C# Language Specification)

Generally speaking, you could convert your logic to extension methods on Rectangle and/or Vector2 and still accomplish your overall goal.

public static class RectangleExtensions 
{
    public static Rectangle MultiplyBy(this Rectangle rect, Vector2 scale)
    {
        return new Rectangle(//...
    }

    public static Rectangle MultiplyBy(this Vector2 scale, Rectangle rect) 
    {
        return new Rectangle(//...
    }
}

// using it
Rectangle output = yourRect.MultiplyBy(yourVector);
0

精彩评论

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