C# 委托Delegate的使用 笔记

时间:2021-09-11 16:24:07

使用delegate总是一头雾水,记录一下笔记,备忘。

主要用于线程间操作UI上的控件,以便使用。或者是大家统一操作入口使用。

 using System.Windows.Forms;

 namespace System.Delegate
{
public static class UIDelegate
{
//------------------
public delegate void myDelegateW(Control str, string s);
public delegate string myDelegateR(Control str);
//------------------ /// <summary>
/// 可以实现对带有Text属性的标准控件进行写操作
/// </summary>
/// <param name="ctr"></param>
/// <param name="str"></param>
public static void writeUIControl(Control ctr, string str)
{
if (ctr.InvokeRequired)
{
myDelegateW mydelegate = new myDelegateW(writeUIControl);
ctr.Invoke(mydelegate, new object[] { ctr, str });
}
else
{
try
{
ctr.Text = str;
}
catch { }
}
}
public static string readUIControl(Control ctr)
{
string ret = string.Empty;
if (ctr.InvokeRequired)
{
myDelegateR mydelegate = new myDelegateR(readUIControl);
ctr.Invoke(mydelegate, new object[] { ctr });
}
else
{
try
{
ret = ctr.Text;
}
catch { }
}
return ret;
}
}
}