Adding custom property to the rectangle class
I need to add a custom property to the Rectangle class. I tried to subclass the Rectangle class but it didn't work. Is there开发者_开发问答 a way to do that. Thanks
You can't inherit from System.Drawing.Rectangle
, because it's not a class, it's a struct
. What you can do is to create your own class (or struct
) that wraps Rectangle
, something like:
class MyRectangle
{
public Rectangle ActualRectangle { get; set; }
public SomeType AdditionalProperty { get; set; }
}
Or you could hide the Rectangle
and provide methods and properties that mirror those of Rectangle
that call them.
You can not extend Rectangle as it's a value type. In my opinion you have 2 choices:
Extension method. Something like this:
public static class Extensions { static object myporpertyvalue = null; public static void SetMyProperty(this Rectangle rect, object value) { myporpertyvalue = value; } public static object GetMyProperty(this Rectangle rect) { return myporpertyvalue ; } }
The type of a property is unknown to me so I put it like an
object
, you need to substitute it with the type you need, naturally.Wrap Rectangle into your custom class.
精彩评论