先在一个类中声名委托
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);
}
}
}
C# 委托的使用方法
猜你喜欢
转载自blog.csdn.net/qq_35106907/article/details/84642814
今日推荐
周排行