【问题标题】:How to create a collection of Shape objects?如何创建 Shape 对象的集合?
【发布时间】:2018-03-21 00:22:10
【问题描述】:

我目前正在做一个C# Winforms中的用户控件,它允许你每次从设计器中添加一个带有属性的图形,以便你更好地理解我,我将参考DataGridView,即每次添加一列时,它有几个参数:标题、文本对齐方式等,都在每个对象列内

嗯,就我而言,我有这个课程:

public class Shape
{
    public int X { get; set; }
    public int Y { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }
    public ShapeType ShapeType { get; set; }
    public Color Color { get; set; }
    public bool Mirrored { get; set; }
}

好吧,我的目标是创建一个 Shape 对象的集合,其中每个 Shape 对象的属性都被封装:

private List<Shape> shapelist = new List<Shape>();
public List<Shape> Shapes
{
    get => this.shapelist;
    set => this.shapelist = value;
}

从 Windows 窗体设计器实例化控件时,我在哪里添加参数:

public ShapesDecoration()
{
     InitializeComponent();
     Init();
}

public void Init()
{
     Shapes[0] = new Shape();
     Shapes[0].Width = 148;
     Shapes[0].Height = 64;
     Shapes[0].X = 20;
     Shapes[0].Y = 20;
     Shapes[0].Color = Color.DodgerBlue;
     Shapes[0].ShapeType = ShapeType.Circle;
}

再调用列表中每个对象的这些参数,例如这里我调用的是第一个位置的Shape对象的参数:

protected override void OnPaint(PaintEventArgs e)
{
     base.OnPaint(e);
     Hector.Framework.Utils.ShapeCollection.FillCircle(e, Shapes[0].Color, Shapes[0].X, Shapes[0].Y, Shapes[0].Width, Shapes[0].Height);
}

我的问题是每次我将控件拖到窗体时,Visual Studio 都会显示一条错误消息,指出 Shape 未标记为可序列化

那么,列表不支持数据类型之类的类吗?

还是我执行错误?

如何创建 Shape 对象的集合,每个对象都有各自的参数?

【问题讨论】:

标签: c# winforms list class collections


【解决方案1】:

简单的添加属性:

[Serializable]
public class Shape
{
    public int X { get; set; }
    public int Y { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }
    public ShapeType ShapeType { get; set; }
    public Color Color { get; set; }
    public bool Mirrored { get; set; }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-16
    相关资源
    最近更新 更多