.NET Framework源码研究系列之---Delegate

断了今生、忘了曾经 提交于 2020-03-25 14:40:21

前言

  曾几何时能看到微软产品的源码简直是天方夜谭,不过现在这却成了现实,微软终于对外开放了它的产品的源代码.抛去开源运动与微软之间的世代情仇,抛去微软这一做法的初衷,这总归是件好事,能够让我们拨开云雾,一窥优秀产品的秘密.

  前两天看到有位仁兄在随笔中的留言,说他以为".NET中的设计模式"是在讲.NET Framework与设计模式的关系,其实不是,不过这也让我想起来自己确实研究过.NET Framework的源码,于是就找打算找时间把自己的心得体会拿出来和大家一起分享.

  今天就先从最容易让人困惑的委托(delegate)开始,让我们步入.NET Framework源码世界,共同学习优秀的程序设计.

  先看委托的定义:用于声明一个引用类型,该引用类型可用于封装命名方法或匿名方法。委托类似于 C++ 中的函数指针;但是,委托是类型安全和可靠的。

  相信看到这段话之后,很多人,包括我自己就开始一起探索委托函数指针,于是各种网文就出现了.但委托到底是什么呢?我们先看一段很简单的代码:

 

    public delegate void OnAction(int flag);

这里我们定义了一个最简单的委托:OnAction.MSDN解释Delegate 类是委托类型的基类,但只有系统和编译器可以显式地从 Delegate 类或 MulticastDelegate 类派生.那么我们可以认为OnAction是从delegate继承过来的,只是不能显式的继承,由系统代做了.

  接下来让我们看一下微软是怎么定义委托的:

 

    [Serializable()]     [ClassInterface(ClassInterfaceType.AutoDual)][System.Runtime.InteropServices.ComVisible(true)]     public abstract class Delegate : ICloneable, ISerializable 

由此可以看出delegate是个抽象类,并且实现了 ICloneable, ISerializable两个接口,并且有ClassInterface(ClassInterfaceType.AutoDual)这么一个属性.这有很多问题.

  首先,委托是个抽象类,所以要使用的必须继承,但是委托又跟整型一样,是一种类型,由此就可以理解问什么"Delegate 类是委托类型的基类,但只有系统和编译器可以显式地从 Delegate 类或 MulticastDelegate 类派生"这句话的意思了,因为不可能从整型继承过来一个子类,那么委托为什么是一个类而不像整型一样是一个结构呢?这个问题下面回答.

  其次,这也是我觉得不理解的地方,委托实现了ICloneable, ISerializable两个接口,也就是说委托可以被克隆和序列化.相信大家没人会写OnAction.Clone();这么一句话.浅表克隆一个委托实在有点费解.不过,如果可以从良好的编程习惯上解释为什么事先ICloneable接口的话,委托对ISerializable的实现就更让人困惑了,因为可能因此导致一些莫名其妙的编译时错误.我曾经遇到这样一个Bug,一个标记序列化的单件实体类包含一个事件(事件默认实现了ISerializable),该事件导致序列化的时候在凡是跟该事件的引用有关的地方全部报出莫名其妙的未标记序列化的错误,最终的解决办法是需要将该事件标记为[NonSerialized].

      下面看一下具体是怎么实现委托的:

 

代码
    public abstract class Delegate : ICloneable, ISerializable    {        //要调用的对象        internal Object _target;        // MethodBase, either cached after first request or assigned from a DynamicMethod        internal MethodBase _methodBase;        // _methodPtr is a pointer to the method we will invoke         // It could be a small thunk if this is a static or UM call         internal IntPtr _methodPtr;        // In the case of a static method passed to a delegate, this field stores        // whatever _methodPtr would have stored: and _methodPtr points to a        // small thunk which removes the "this" pointer before going on        // to _methodPtrAux.         internal IntPtr _methodPtrAux;        // This constructor is called from the class generated by the         //  compiler generated code        protected Delegate(Object target, String method)        {            if (target == null)                throw new ArgumentNullException("target");            if (method == null)                throw new ArgumentNullException("method");            // This API existed in v1/v1.1 and only expected to create closed            // instance delegates. Constrain the call to BindToMethodName to             // such and don't allow relaxed signature matching (which could make            // the choice of target method ambiguous) for backwards            // compatibility. The name matching was case sensitive and we            // preserve that as well.             if (!BindToMethodName(target, Type.GetTypeHandle(target), method,                                  DelegateBindingFlags.InstanceMethodOnly |                                  DelegateBindingFlags.ClosedDelegateOnly))                throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));        }        // This constructor is called from a class to generate a        // delegate based upon a static method name and the Type object        // for the class defining the method.         protected unsafe Delegate(Type target, String method)        {            if (target == null)                throw new ArgumentNullException("target");            if (!(target is RuntimeType))                throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType"), "target");            if (target.IsGenericType && target.ContainsGenericParameters)                throw new ArgumentException(Environment.GetResourceString("Arg_UnboundGenParam"), "target");            if (method == null)                throw new ArgumentNullException("method");            // This API existed in v1/v1.1 and only expected to create open            // static delegates. Constrain the call to BindToMethodName to such            // and don't allow relaxed signature matching (which could make the            // choice of target method ambiguous) for backwards compatibility.             // The name matching was case insensitive (no idea why this is            // different from the constructor above) and we preserve that as             // well.             BindToMethodName(null, target.TypeHandle, method,                             DelegateBindingFlags.StaticMethodOnly |                             DelegateBindingFlags.OpenDelegateOnly |                             DelegateBindingFlags.CaselessMatching);        }        // Protect the default constructor so you can't build a delegate        private Delegate()        {        }

上面代码显示委托类包含4个internal类型的字段,从其注释我们大致可以看出_target是我们要调用的对象,_methodBase是给委托赋值时传递的方法,_methodPtr是指向该方法的指针,_methodPtrAux同静态类型委托的methodPtr指向的内容一样,只是少了对象的引用. 在看委托类的三个构造函数,一个是私有的,是用来防止实例化的,另外2个差不多,做的事情是把一个方法绑定到一个对象上.这里的方法应该是我们赋给委托的方法,对象则是编译器自己来维护的对象.这里调用了一个方法BindToMethodName,在源码中看不到实现,仅能看到如下内容:

        [MethodImplAttribute(MethodImplOptions.InternalCall)]        private extern bool BindToMethodName(Object target, RuntimeTypeHandle methodType, String method, DelegateBindingFlags flags);

MethodImplAttribute标签表明了该方法为CLR内部方法,具体是什么,我们不得而知.此类的方法还有很多,就不一一例举.说到这个地方,我们可以发现上面说的"OnAction是从delegate继承过来的"和"Delegate 类是委托类型的基类"并不正确,正确的理解应该是delegate类在内部管理了一个用于绑定方法的对象,这点也可以从OnAction反汇编出来的构造函数看出:

代码
.method public hidebysig specialname rtspecialname         instance void  .ctor(object 'object',                             native int 'method') runtime managed{} // end of method OnAction::.ctor

另外delegate中还有一个静态方法:

public static Delegate CreateDelegate(Type type, Object firstArgument, MethodInfo method, bool throwOnBindFailure)

该方法前后有11个重载,其方法体里无一不包括:

 

代码
            Delegate d = InternalAlloc(type.TypeHandle);            if (!d.BindToMethodInfo(firstArgument, method.MethodHandle, method.DeclaringType.TypeHandle,                                    DelegateBindingFlags.RelaxedSignature))            {                if (throwOnBindFailure)                    throw new ArgumentException(Environment.GetResourceString("Arg_DlgtTargMeth"));                d = null;            }

这样一段代码.其中InternalAlloc,BindToMethodInfo与BindToMethodName一样,都属于CLR内部方法.具体是什么一样看不出,只能大致猜测CLR内部生成了一个委托对象,然后将我们定义的委托签名,方法,方法引用等一些内容交给委托类来维护.

 

  通过以上分析,我们发现如它的定义,委托本质上是一个类,它的职责是代替我们管理维护方法调用.这一切无论从功能,还是外面,其实跟函数指针没有半点关系.至此,相信大家对delegate有了不一样的认识,同时也发现C#仅仅是CLR的一层外壳,并没有涉及到很核心的内容.

 

 

 

 

       以上仅仅是我个人的一点看法,由于本人水平有限,认识上难免有不正确的地方,如果你有更好的见解,敬请指正.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!