用于从外部线程更改标签文本的 C# 通用方法。

标签 c# windows forms

好吧,所以这是(希望)一个非常简单的修复,但我正在尝试创建一个通用方法来允许外部访问标签,现在 Windows 文档确实针对单个案例给出了一个示例

delegate void SetTextCallback(string text);
...some other code ...
private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.textLable.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.textLable.Text = text;
        }
    }

但是我想创建一些更通用的东西,我可以沿着指向对象的指针传递一些东西,但是 Windows 窗体中的文本标签不允许这样做。理想情况下,对于这种情况,我想要一些沿着这些方向做的事情(这显然不适用于表格,只是为了解释目的)

...code...
private void SetText(string text, Label* lablePointer)
{
    if (this.lablePointer.InvokeRequired)
    {
        SetTextCallback d = new SetTextCallback(SetText);
        this.Invoke(d, new object[] { text });
    }
    else
    {
        this.lablePointer.Text = text;
    }
}

有没有办法做到这一点?我一直在寻找,但似乎没有任何地方得到回答。

最佳答案

你不需要指针——你可以这样做:

private void SetText(string text, Control control)
{
    if (control.InvokeRequired)
        control.Invoke(new Action(() => control.Text = text));
    else
        control.Text = text;
}

您可以使用 Control而不是 Label因为Text属性继承自 Control ( Label 派生自 Control )。这使它的用途更加通用。

你不需要指针因为Label (和 Control )是引用类型,这意味着对 Label 的引用的副本当 SetText() 时,对象被压入堆栈被调用,这与在 C/C++ 中传递指针具有类似的效果。

(我猜你是一个正在转向 C# 的 C/C++ 程序员。)

关于用于从外部线程更改标签文本的 C# 通用方法。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39534439/

相关文章:

c# - WorkItemCollection 项目访问速度太慢

c# - 缺少类型 Microsoft.CSharp.RuntimeBinder.Binder

windows - cmd 不显示某些文件

ruby - Mechanize 在登录页面找不到表单

javascript - 在 JavaScript 中的表单字段旁边打印文本

Python Mechanize 表单提交

c# - MySql.Data.MySqlClient 调用存储过程时出错

Windows 计划任务不适用于 PHP 脚本

c++ - 在 DLL 中运行的工作线程在应用程序关闭时被杀死,然后才能正常关闭它们

c# - 切换时两个 slider 都会继续监听