反思说,接口方法是在执行类型的虚拟,当他们都没有? [英] Reflection says that interface method are virtual in the implemented type, when they aren't?

查看:183
本文介绍了反思说,接口方法是在执行类型的虚拟,当他们都没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个单元测试

    public bool TestMethodsOf<T, I>()
  {
   var impl = typeof(T);
   var valid = true;

   foreach (var iface in impl.GetInterfaces().Where(i => typeof(I).IsAssignableFrom(i)))
   {

    var members = iface.GetMethods();

    foreach (var member in members)
    {
     Trace.Write("Checking if method " + iface.Name + "." + member.Name + " is virtual...");
     var implMember = impl.GetMethod(member.Name, member.GetParameters().Select(c => c.ParameterType).ToArray());
     if (!implMember.IsVirtual)
     {
      Trace.WriteLine(string.Format("FAILED"));
      valid = false;
      continue;
     }

     Trace.WriteLine(string.Format("OK"));
    }
   }
   return valid;
  }



我用

which I call by

Assert.IsTrue(TestMethodsOf<MyView, IMyView>());



我要确保所有从接口的方法声明为虚拟的。究其原因是因为我施加spring.net方面,它仅适用于虚拟方法。

I want to ensure that all the methods from the interface are declared as virtual. The reason is because I'm applying a spring.net aspect and it will only apply to virtual methods.

我遇到的问题是,implMember.IsVirtual总是如此,即使他们不声明为因此在声明类型。

The problem I'm having is that implMember.IsVirtual is always true, even when they are not declared as so in the declaring type.

什么是错我的TestMethodsOf逻辑?

What is wrong with my TestMethodsOf logic?

干杯

推荐答案

在接口中声明的所有方法都被标记为虚拟抽象,以及实现在类接口方法的所有方法都标为虚拟决赛,所以CLR知道它不能只是直接调用它们 - 它在运行时做虚函数表查找调用正确的实现。该接口实现仍然是虚拟的,但因为他们是最终不能覆盖他们。

All methods declared in an interface are marked as virtual abstract, and all methods that implement interface methods in classes are marked as virtual final, so the CLR knows it can't just call them directly - it has to do vtable lookups at runtime to call the right implementation. The interface implementations are still virtual, but you can't override them as they're final.

作为一个例子,下面的C#定义:

As an example, the following C# definition:

public interface IInterface {
    void Method();
}

public class Class : IInterface {
    public void Method() {}
}

编译以下IL:

.class public interface abstract IInterface {
    .method public abstract virtual instance void Method() {}
}

.class public Class extends [mscorlib]System.Object implements IInterface {
    .method public specialname rtspecialname instance void .ctor() {}
    .method public virtual final instance void Method() {}
}

这篇关于反思说,接口方法是在执行类型的虚拟,当他们都没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆