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);
精彩评论