有没有办法向矩形结构添加额外的值?

Is there a way to add additional values to the rectangle struct?

我想给矩形添加额外的值。例如 "Name" 字符串。

像这样:

Rectangle MyRectangle = new Rectangle(Y, X, Width, Height, Name)

这可能吗?

Rectangle class.

中有两个重载构造函数
public Rectangle(Point location, Size size);
public Rectangle(int x, int y, int width, int height);

但是Rectangleclass中没有构造函数参数new Rectangle([int], [int], [int], [int], [string])

你可以尝试在class.

中使用复合public Rectangle rect { get; set; }属性

然后使用构造函数设置Rectangle对象和Name

public class CustomerRectangle 
{
    public Rectangle Rect { get; set; }
    public string Name { get; set; }
    public CustomerRectangle(int llx, int lly, int urx, int ury,string name) 
    {
        Rect = new Rectangle(llx, lly, urx, ury);
        Name = name;
    }
}

那么你可以使用

CustomerRectangle  MyRectangle = new CustomerRectangle (Y, X, Width, Height, Name);

//MyRectangle.Name; use Name property 
//MyRectangle.Rect; use Rectangle

我假设您正在使用 System.Drawing 命名空间中的构造函数: https://docs.microsoft.com/en-us/dotnet/api/system.drawing.rectangle?view=netframework-4.7.2

无法向该结构添加额外字段。您可以做的是创建自己的 class 或包含更多 .

的结构
public class NamedRectangle
{
    public string Name { get; set; }

    public double X { get; set; }

    public double Y { get; set; }

    public double Width { get; set; }

    public double Height { get; set; }

    public NamedRectangle(double x, double y, double width, double height, string name)
    {
        Name = name;
        X = x;
        Y = y;
        Width = width;
        Height = height;
    }
}

我看到其他人提供了很好的示例,但是如果出现 Cannot inherit from sealed type 错误,以下示例可能会对您有所帮助:

public class myRectangle
{

    private Rectangle newRectangle = new Rectangle();
    private string name;

    public myRectangle Rectangle(Int32 Y, Int32 X, Int32 Height, Int32 Width, string name )
    {
       newRectangle.Y = Y;
       newRectangle.X = X;
       newRectangle.Height = Height;
       newRectangle.Width = Width;
       this.name = name;

       return this;
    }
}