我正在开发剧院预订软件。我使用的是Windows Forms,席位由2维数组表示。我按如下所示绘制按钮:
public void DrawSeats()
{
// pnl_seats is a Panel
pnl_seats.Controls.Clear();
// Here I store all Buttons instance, to later add all buttons in one call (AddRange) to the Panel
var btns = new List<Control>();
// Suspend layout to avoid undesired Redraw/Refresh
this.SuspendLayout();
for (int y = 0; y < _seatZone.VerticalSize; y++)
{
for (int x = 0; x < _seatZone.HorizontalSize; x++)
{
// Check if this seat exists
if (IsException(x, y))
continue;
// Construct the button with desired properties. SeatSize is a common value for every button
var btn = new Button
{
Width = SeatSize,
Height = SeatSize,
Left = (x * SeatSize),
Top = (y * SeatSize),
Text = y + "" + x,
Tag = y + ";" + x, // When the button clicks, the purpose of this is to remember which seat this button is.
Font = new Font(new FontFamily("Microsoft Sans Serif"), 6.5f)
};
// Check if it is already reserved
if (ExistsReservation(x, y))
btn.Enabled = false;
else
btn.Click += btn_seat_Click; // Add click event
btns.Add(btn);
}
}
// As said before, add all buttons in one call
pnl_seats.Controls.AddRange(btns.ToArray());
// Resume the layout
this.ResumeLayout();
}
但是已经有20 x 20的座位区(400个按钮),它花了将近1分钟的时间来绘制它,并且在调试中我检查了性能的不足是按钮的实例化。
有没有办法使它更快?也许在实例化过程中禁用所有事件,或者也禁用另一个具有Click事件的轻量控件?
更新:lbl
是一个测试,正确的是btn
,抱歉。
更新2:
这里是IsException
和ExistsReservations
方法:
private bool IsException(int x, int y)
{
for (var k = 0; k < _seatsExceptions.GetLength(0); k++)
if (_seatsExceptions[k, 0] == x && _seatsExceptions[k, 1] == y)
return true;
return false;
}
private bool ExistsReservation(int x, int y)
{
for (var k = 0; k < _seatsReservations.GetLength(0); k++)
if (_seatsReservations[k, 0] == x && _seatsReservations[k, 1] == y)
return true;
return false;
}
假设您将保留和排除的数组更改为
public List<string> _seatsExceptions = new List<string>();
public List<string> _seatsReservations = new List<string>();
您可以在列表中添加排除项和保留项,例如
_seatsExceptions.Add("1;10");
_seatsExceptions.Add("4;19");
_seatsReservations.Add("2;5");
_seatsReservations.Add("5;5");
您的排除和保留检查可以更改为
bool IsException(int x, int y)
{
string key = x.ToString() + ";" + y.ToString();
return _seatsExceptions.Contains(key);
}
bool ExistsReservation(int x, int y)
{
string key = x.ToString() + ";" + y.ToString();
return _seatsReservations.Contains(key);
}
当然,我不知道您是否可以在程序中进行此更改。但是,请考虑早晚更改阵列上的搜索。
编辑我进行了一些测试,虽然20x20按钮的虚拟网格可以令人满意地工作(平均31毫米0.775ms),但是较大的网格会明显放慢速度。在200x50分辨率下,时间跳到10秒(平均1,0675)。因此,也许需要一种不同的方法。绑定的DataGridView可能是一个更简单的解决方案,并且相对容易处理。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句