动态覆盖c#中的抽象方法

ng.*_*ng. 2 c#

我有以下抽象类,不能更改.

public abstract class AbstractThing {
   public String GetDescription() {
      return "This is " + GetName();
   }
   public abstract String GetName();
}
Run Code Online (Sandbox Code Playgroud)

现在我想从中实现一些新的动态类型.

AssemblyName assemblyName = new AssemblyName();
assemblyName.Name = "My.TempAssembly";
AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder =  assemblyBuilder.DefineDynamicModule("DynamicThings");
TypeBuilder typeBuilder = moduleBuilder.DefineType(someName + "_Thing", 
                TypeAttributes.Public | 
                TypeAttributes.Class, 
                 typeof(AbstractThing));
MethodBuilder methodBuilder = typeBuilder.DefineMethod("GetName",    
                MethodAttributes.Public | 
                MethodAttributes.ReuseSlot |
                MethodAttributes.Virtual | 
                MethodAttributes.HideBySig,
                null,
                Type.EmptyTypes);

ILGenerator msil = methodBuilder.GetILGenerator();

msil.EmitWriteLine(selectionList);
msil.Emit(OpCodes.Ret);
Run Code Online (Sandbox Code Playgroud)

但是当我尝试实例化via时

typeBuilder.CreateType();
Run Code Online (Sandbox Code Playgroud)

我得到一个例外,说GetName没有实现.我在这里做错了吗?我看不出问题.

另外,通过名称实例化这样一个类的限制是什么?例如,如果我尝试通过"My.TempAssembly.x_Thing"实例化它是否可用于实例化而不生成Type?

Pen*_*puu 8

动态创建的函数有错误的返回类型.它应该是string代替void:

typeBuilder.DefineMethod("GetName",   
MethodAttributes.Public | 
MethodAttributes.ReuseSlot |
MethodAttributes.Virtual | 
MethodAttributes.HideBySig,
typeof(string),
Type.EmptyTypes);
Run Code Online (Sandbox Code Playgroud)