委托类Delegate,位于System命名空间下,是所有声明的委托类型的基类.
例如我们声明了一个委托类型Func<int,bool> MyFunc或者 delegate bool MyDel(int i);
该类型声明成功后,该委托类自动继承System.MulticastDelegate,其包含了构造方法、BeginInvoke、EndInvoke、Invoke方法。
class MyDel:System.MulticastDelegate
{
void Invoke(string value);
IAsyncResult BeginInvoke(string value,AsyncCallback callback,Object object);
void EndInvoke(IAsyncResult result);
}
System.MulticastDelegate 类
下面我们来看看借助.Net Reflector工具来查看类库中的MulticastDelegate类
public abstract class MulticastDelegate : Delegate
由此我们可以看出继承关系:MyDel –> MulticastDelegate–> Delegate.
static void Main(string[] args)
{
try
{
//多播委托应用一,
//根据输入的同一参数,处理委托引用的多个方法,达到处理不同动作的需求
//定义有一个类型参数为Action<string>的泛型List<T>,并以其引用的方法为其赋值:M1,M2,M3
List<Action<string>> handlers = new List<Action<string>> { M1, M2 }; handlers.Add(M3);
foreach (var del in handlers)
{
del("stringparam");
}
//多播委托应用二
//根据输入的同一参数,对多个委托引用的所有方法返回值进行判断是否为真
//声明一个委托对象
Func<int, bool> func = M1;
//添加委托对象的方法链表
func += M2;
//调用列表invocation list
//通过Func<T>对象的GetinvocationList方法,可以返回委托对象的方法链表
Delegate[] dellist = func.GetInvocationList();
//多播委托调用多个方法的顺序并不确定,通过DynamicInvoke()方法,逐一动态执行方法链表中的当前方法
List<bool> results = dellist.Select(del => (bool)del.DynamicInvoke(1)).ToList();
//或者用foreach循环逐一运行都播委托中的方法,返回结果给string[],和上面select扩展方法得到的结果一致
List<bool> ressults_all = new List<bool>();
bool result = false;
foreach (Func<bool,int> del in dellist)
{
result = del.Invoke(1);
ressults_all.Add(result);
}
//上面两种方法都可以获取多播委托对应方法链的返回结果,但下一种方法资源开销小,建议使用.
//或者将LINQ语句先墙砖,再执行如下:
//List<bool> results = dellist.Select(del =>((Func<int,bool>)del).Invoke(1)).ToList();
//判断所有方法的返回结果是否都为true
bool bl_return = ressults_all.Contains(false);
//多播委托应用三
//模拟程序执行过程遇到异常
throw new Exception("boolshit,I occur a Physical Error");
}
catch (Exception ex)
{
//模拟try主程序中遇到错误,catch中的异常处理流程,定义一个委托,将错误对象传进去,引用多个不同的方法模拟错误处理过程
Action<Exception> errorHandler = InformCustomer;
errorHandler += DealWithError;
errorHandler += ClearErr;
errorHandler(ex);
}
finally
{}
}
static bool M1(int i1)
{
return false;
}
static bool M2(int i1)
{
return true;
}
static void M1(string s1)
{
//deal M1 action
}
static void M2(string s2)
{
//deal order infor
}
static void M3(string s3)
{
//clear msg
}
static void InformCustomer(Exception ex)
{
//inform customer
}
static void DealWithError(Exception ex)
{
//deal with error
}
static void ClearErr(Exception ex)
{
//clear error msg
}
public delegate int MyDel(int i);
Delegate[] dellist = myaction.GetInvocationList();
List<int> result_Dellist_select = dellist.Select(del => ((Func<int, int>)del).Invoke(1)).ToList();
上面的demo,Func<int,int>和Mydel都是自定义的委托类型,del类型是Delegate,所以将del强转成成Mydel或Func<int,int>,就可以直接调用invoke执行委托引用的方法了!!!