C#使用通用T作为按钮委托
c#
我正在失去理智,试图弄清楚这一点。我正在开发一个大型 Windows 应用程序,它需要主窗体中的所有控件近乎实时地更新它们的值。我将这个连续方法的处理移到它自己的线程中,这通常很好,但我知道它需要我创建一个 Delegate 来设置我在不同线程中创建的控件。但是,我有一系列按钮需要为每个按钮设置相同的各种属性,但具有不同的值。我想我可以设置一个通用类型为 Button 的 Delegate,所以我可以在更新其属性时简单地传入正确的按钮控件。但我错过了一些东西,它不起作用:
//If this is wrong, please let me know
private delegate void SafeButtonText<T>(string value) where T : Button;
private void SetButtonTextSafe<T>(string value) where T : Button
{
//Using the generic Button passed in, set its values
if (T.InvokeRequired) //This doesn't compile
{
var d = new SafeButtonText<T>(SetButtonTextSafe<T>);
T.Invoke(d, new object[] { value }); //This doesn't compile
}
else
T.Text = value; //This doesn't compile
}
我以为我可以这样使用它(这似乎不可能)
SetButtonTextSafe<qualityButton>(values[0]);
如果这是可能的,或者如果有更好的方法可以做到这一点,请随时详细告诉我。(如果我可以在按钮上使用它,我也会为其他控件类型创建另一个委托)
提前致谢。
回答
类型就是……一种类型。您无法调用它的实例,因为您没有实例。它只是反映的元数据。
您需要将按钮的实例传递给您的方法。
private delegate void SafeButtonText<T>(T button, string value) where T : Button;
private void SetButtonTextSafe<T>(T button, string value) where T : Button
{
//Using the generic Button passed in, set its values
if (button.InvokeRequired) //This now compiles
{
var d = new SafeButtonText<T>(SetButtonTextSafe<T>);
button.Invoke(d, new object[] { value }); //This now compiles
}
else
button.Text = value; //This now compiles
}