Вызов метода базового класса игнорируя переопределенный метод в производном классе - C#

Узнай цену своей работы

Формулировка задачи:

Как вызвать метод базового класса игнорируя переопределенный метод в производном классе. PS переопределение метода в производном классе удалить нельзя, вшит в dll
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace ConsoleApplication1
  7. {
  8. public class Person
  9. {
  10. protected string ssn = "444-55-6666";
  11. protected string name = "John L. Malgraine";
  12. public virtual void GetInfo()
  13. {
  14. Console.WriteLine("Name: {0}", name);
  15. Console.WriteLine("SSN: {0}", ssn);
  16. }
  17. }
  18. class Employee : Person
  19. {
  20. public string id = "ABC567EFG";
  21. public override void GetInfo()
  22. {
  23. // Calling the base class GetInfo method:
  24. base.GetInfo();
  25. Console.WriteLine("Employee ID: {0}", id);
  26. }
  27. }
  28. class TestClass
  29. {
  30. static void Main()
  31. {
  32. Employee E = new Employee();
  33. E.GetInfo();
  34. Console.ReadKey();
  35. }
  36. }
  37. }
изменить тело классов базового и производного нельзя.

Решение задачи: «Вызов метода базового класса игнорируя переопределенный метод в производном классе»

textual
Листинг программы
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Reflection.Emit;
  6.  
  7. namespace System.Reflection
  8. {
  9.     public static class MethodInfoExtensions
  10.     {
  11.         public static object InvokeNotOverride(this MethodInfo MethodInfo, object Object, params object[] Arguments)
  12.         { // void return, this parameter
  13.             var Parameters = MethodInfo.GetParameters();
  14.  
  15.             if (Parameters.Length == 0)
  16.             {
  17.                 if (Arguments != null && Arguments.Length != 0) throw new Exception("The number of arguments does not match the number of parameters");
  18.             }
  19.             else {
  20.                 if (Parameters.Length != Arguments.Length) throw new Exception("The number of arguments does not match the number of parameters");
  21.             }
  22.  
  23.             Type ReturnType = null;
  24.             if (MethodInfo.ReturnType != typeof(void))
  25.             {
  26.                 ReturnType = MethodInfo.ReturnType;
  27.             }
  28.  
  29.             var Type = Object.GetType();
  30.             var DynamicMethod = new DynamicMethod("", ReturnType, new Type[] { Type, typeof(Object) }, Type);
  31.             var ILGenerator = DynamicMethod.GetILGenerator();
  32.             ILGenerator.Emit(OpCodes.Ldarg_0); // this
  33.  
  34.             for (var i = 0; i < Parameters.Length; i++)
  35.             {
  36.                 var Parameter = Parameters[i];
  37.  
  38.                 ILGenerator.Emit(OpCodes.Ldarg_1); // load array argument
  39.  
  40.                 // get element at index
  41.                 ILGenerator.Emit(OpCodes.Ldc_I4_S, i); // specify index
  42.                 ILGenerator.Emit(OpCodes.Ldelem_Ref); // get element
  43.  
  44.                 var ParameterType = Parameter.ParameterType;
  45.                 if (ParameterType.IsPrimitive)
  46.                 {
  47.                     ILGenerator.Emit(OpCodes.Unbox_Any, ParameterType);
  48.                 }
  49.                 else if (ParameterType == typeof(object))
  50.                 {
  51.                     // do nothing
  52.                 }
  53.                 else {
  54.                     ILGenerator.Emit(OpCodes.Castclass, ParameterType);
  55.                 }
  56.             }
  57.  
  58.             ILGenerator.Emit(OpCodes.Call, MethodInfo);
  59.  
  60.             var TestLabel = ILGenerator.DefineLabel();
  61.  
  62.             ILGenerator.Emit(OpCodes.Ret);
  63.             return DynamicMethod.Invoke(null, new object[] { Object, Arguments });
  64.         }
  65.     }
  66.     class Program
  67.     {
  68.         class BaseClass
  69.         {
  70.             public virtual void Test()
  71.             {
  72.                 Console.WriteLine("Test() from BaseClass");
  73.             }
  74.         }
  75.  
  76.         class OverridingClass : BaseClass
  77.         {
  78.             public override void Test()
  79.             {
  80.                 Console.WriteLine("Test() from OverridingClass");
  81.             }
  82.         }
  83.  
  84.         public static void Main()
  85.         {
  86.             var d = new OverridingClass();
  87.             //typeof(BaseClass).GetMethod("Test").Invoke(d, null);
  88.             typeof(BaseClass).GetMethod("Test").InvokeNotOverride(d, null);
  89.             Console.ReadKey();
  90.         }
  91.      
  92.     }
  93. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

5   голосов , оценка 4 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы