创建一个 class 以在运行时实现接口(如代理 class)

Create a class to implement interface (like a proxy class) at runtime

首先,我将 Visual Studio 2005 与 .NET Framework 2.0 一起使用。不幸的是,我不能使用最新版本的 VS/.NET。

我需要能够在运行时创建一个 class 来继承另一个 class 并实现某个接口。问题是需要继承的 class 具有相同的接口方法签名。

例如:

public interface ITestInterface
{
    void Test1();
    string Test2(int a, string b);
}

public class TestClass
{
    public void Test1() { ... }
    public string Test2(int a, string b) { ... }
    public void AnotherMethod() { ... }
}

如果我创建另一个 class,例如:

public class AnotherClass : TestClass, ITestInterface
{
}

在 Visual Studio 2005 中,它的编译没有任何问题,因为 TestClass 已经实现了所有接口的 methods/functions。

如果我检查为此 class 生成的 MSIL 代码,我可以看到它创建了一个名为 AnotherClass 的类型,它继承自 TestClass 并实现了 ITestInterface,正如我所期望的那样(没有 methods/functions 实现为它们已经在基础中实现 class).

像这样在运行时通过代码尝试这样做:

object GetProxy(Type iface, Type obj)
{
    string name = obj.Name + "Proxy";
    AssemblyBuilder assyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(name), AssemblyBuilderAccess.Run);
    ModuleBuilder modBuilder = assyBuilder.DefineDynamicModule(name);
    TypeBuilder typeBuilder = modBuilder.DefineType(name, TypeAttributes.Public | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.BeforeFieldInit, obj, new Type[] { iface });

    Type proxyType = typeBuilder.CreateType(); // Exception here

    return Activator.CreateInstance(proxyType);
}

引发以下异常:

An unhandled exception of type 'System.TypeLoadException' occurred in mscorlib.dll

Additional information: Method 'Test1' in type 'TestClassProxy' from assembly 'TestClassProxy, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.

我不明白为什么运行时会强制我实现接口的方法,如果它们已经在基础中实现的话 class。

你有什么想法吗?也许我缺少一个选项?

根据 Brian 在 this link and this one 中找到的信息,将基础 class methods/functions 标记为 virtual 可以解决此特定问题。

我知道这对基础 classes 提出了要求,但这对我来说是可以接受的。