关于在C#

关于在C#,c#,reflection,overriding,derived-class,C#,Reflection,Overriding,Derived Class,我应该如何区分派生类是否实现了方法的重写 class BaseClass { public virtual void targetMethod() { return; } } class DerivedClass:BaseClass { public bool isOverrideTargetMethod() { //Here, I wants to judge whether DerivedClass is overrided targetMethod

我应该如何区分派生类是否实现了方法的重写

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();
     }
} 

首先,从设计的角度来看,你想做的不是很好,但是如果你真的想做,反射就是答案

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);

在派生类中添加isOverrideTargetMethod布尔属性,并在派生类中的override方法中指定true我不想添加特殊属性。因为我想通过大量方法判断重写,所以反射很方便。谢谢。反射在运行时判断它很慢。例如,请给我以下想法・ 如何在编译时进行静态判断・ 如何缓存reflectionty以消除类似的问题,typeof关键字采用编译时类型标识符var isDerived=typeof(DerivedClass).GetMember(“targetMethod”,BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly).Length==0;有没有不使用文字“targetMethod”的方法?请参考链接中“Salvatore Previti”给出的解决方案