0

What should I do to distinguish it whether a derived class implements overriding of a method?

class BaseClass
{
    public virtual void targetMethod() { return; }
}

class DerivedClass:BaseClass
{
    public bool isOverrideTargetMethod()
    {
        //Here, I wants to judge whether DerivedClass is overrided targetMethod.
     }
     public override void targetMethod()
     {
         base.targetMethod();
     }
} 
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
kyouno
  • 49
  • 1
  • 7

1 Answers1

0

First of all what you are trying to do is not very good in design perspective but if you really want to do Reflection is the answer.

using System.Reflection;

Type classType = typeof(DerivedClass);
MethodInfo method = classType.GetMethod("targetMethod");
if (method.DeclaringType == typeof(BaseClass))
    Console.WriteLine("targetMethod not overridden.");
else
Console.WriteLine("targetMethod is overridden " + method.DeclaringType.Name);
AKN
  • 416
  • 2
  • 5
  • Because I want to judge overriding by great many methods, the reflection is convenient.Thank you. – kyouno Mar 14 '17 at 05:22
  • The reflection is slow to judge it for run time. For example, please give me the following ideas ・ How to judge statically in a compile time ・ How to cache of reflection – kyouno Mar 14 '17 at 05:29
  • Try to de somthing like this, The typeof keyword takes a compile-time type identifier var isDerived = typeof(DerivedClass).GetMember("targetMethod", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly).Length == 0; – AKN Mar 14 '17 at 05:36
  • Is there the way not to use Literal "targetMethod"? – kyouno Mar 14 '17 at 05:38
  • Plese refer to solution given by "Salvatore Previti" at link [link](http://stackoverflow.com/questions/2932421/detect-if-a-method-was-overridden-using-reflection-c) – AKN Mar 14 '17 at 05:46
  • It was solved by a linked article. Thank you. ((Action)targetMethod).Method.DeclaringType == typeof(BaseClass) – kyouno Mar 14 '17 at 07:27