委托的使用场景积累:
1、无继承关系的两个窗体,窗体(A)唤醒另一个窗体(B),该窗体B需要用到窗体A中某个自定义控件的公有方法时,在dlg.show()之前注册委托
先在一个类中声名委托
delegate string TestDelegate(); //参数要和方法参数对应
delegate string TestDelegateReturnString(string value); //调用GetValue时的委托
public class TestSpace
{
public TestSpace(){
}
public string GetValue(string value)
{
return value;
}
public string GetMethod1()
{
return "Method1";
}
public string GetMethod2()
{
return "Method2";
}
}
private void button2_Click(object sender, EventArgs e)
{
TestSpace obj = new TestSpace();
//实例化TestDelegate委托,调用委托中的GetValue方法
TestDelegateReturnString method = (TestDelegateReturnString)Delegate.CreateDelegate(typeof(TestDelegateReturnString), obj, "GetValue");
//其实委托的好处就是方法可以是动态创建的,GetValue可以作为参数传进来
Console.WriteLine(method.Method.ToString()); //获取当前委托调用的方法
Console.WriteLine(obj.GetValue("TestObjGetValue")); //用实例化对象调用,只能调用指定的方法。
Console.WriteLine(method.Invoke("TestDelegateRuturnString-method")); //委托调用方法
TestDelegate method1 = new TestDelegate(obj.GetMethod1); //另一种创建委托的方法 - 调用某个具体方法
TestDelegate method2 = new TestDelegate(obj.GetMethod2);
//创建委托链
TestDelegate chain = null;
chain += method1;
chain += method2;
//委托数组 数组中的元素使用委托链
Delegate[] arr = chain.GetInvocationList();
//遍历委托链
foreach (TestDelegate item in arr)
{
try
{
Console.WriteLine(item());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}