c# - c# 中标签的引用(或指针)数组

标签 c# winforms user-interface

假设我有一个包含大量温度读数的表单,那么在设计器中:

this.lblTemperatureDevice01 = new System.Windows.Forms.Label();
this.lblTemperatureDevice02 = new System.Windows.Forms.Label();
this.lblTemperatureDevice03 = new System.Windows.Forms.Label();
// ...
this.lblTemperatureDevice50 = new System.Windows.Forms.Label();

在主窗体代码中,如何将标签添加到数组,以便我可以在计时器事件中使用循环更新标签,例如:

private void tmrUpdateLabels_Tick(object sender, EventArgs e)
{
    // Disable timer
    tmrUpdateLabels.Enabled = false;
    if (m_bExiting)
        return;

    // Update temperatures (if device has returned a reading)
    for (int device = 0; device < MAX_DEVICES; device++)
    {
        if (m_aHasNewReading[device])
        {
            m_aHasNewReading[device] = false;
            labels[device].Text = m_aTemperature[device].ToString();
        }
    }

    // Restart timer
    tmrUpdateLabels.Enabled = true;
}

如何创建标签[MAX_DEVICES] 数组?我必须使用:

private Label[] labels = new Label[MAX_DEVICES];

或者有没有办法在不创建新标签的情况下获取对现有标签的引用(或指针)?来自 C++ 背景,我可能只是将每个标签的地址存储在一个数组中。

最佳答案

您可以从表单的控件集合中获取所有标签

private Label[] labels;
.ctor
{
    InitializeComponent();
    labels = this.Controls.OfType<Label>()
            .Where(lbl => lbl.Name.StartsWith("lblTemperatureDevice"))
            .OrderBy(lbl => int.Parse(lbl.Name.Replace("lblTemperatureDevice","")))
            .ToArray();
}

关于c# - c# 中标签的引用(或指针)数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29366900/

相关文章:

c# - 多次实现协变接口(interface) : is this behavior properly defined?

c# - 如果数据库表更新/插入,如何让 Windows C# 控件自动更新?

c# - 无法绑定(bind)到实现 ICollection<T> 的对象的属性

c# - 获取多个控件并更改属性

c++ - 在单独的 GUI 类(菜单、工具栏等)之间共享操作的最佳方式是什么?

html - Wordpress - 使后端更加用户友好。自定义字段?

c# - 清洁绳子?有没有更好的方法呢?

c# - 在多个函数之间使用对象

C# 文件选择和网络访问?

ios - 代码 8 : Auto layout Leading & Trailing