Telerik blogs

Yesterday a colleague of mine asked me a question about how to invoke a method of a base class' base class. Although it is possible it is not a good idea (read more on stackoverflow). The basic idea is to avoid MethodDesc::IsVtableMethod() check (see Shared Source Common Language Infrastructure). That said here is the code.

 

using System;
 
namespace BaseBaseDemo
{
    class A
    {
        public virtual void M(string text)
        {
            Console.WriteLine("A:M({0})", text);
        }
    }
 
    class B : A
    {
        public override void M(string text)
        {
            Console.WriteLine("B:M({0})", text);
        }
    }
 
    class C : B
    {
        delegate void DelM(string text);
 
        public override void M(string text)
        {
            var ptr = this.GetType()
                        .BaseType.BaseType
                        .GetMethod("M").MethodHandle.GetFunctionPointer();
 
            var m = typeof(DelM)
                    .GetConstructor(new Type[] { typeof(object), typeof(IntPtr) })
                    .Invoke(new object[] { this, ptr }) as DelM;
 
            m(text); // base.base.M(text);
            base.M(text);
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            new C().M("test");
        }
    }
}

 


Comments

Comments are disabled in preview mode.