简体   繁体   English

C#dynamic + System.Reflection.Emit =不要混用?

[英]C# dynamic + System.Reflection.Emit = do not mix?

Why does the code like this: 为什么代码如下:

using System;
using System.Reflection;
using System.Reflection.Emit;

class Program
{
  static Type CreateDynamicType()
  {
    var typeBuilder = AppDomain.CurrentDomain
      .DefineDynamicAssembly(
        name: new AssemblyName("FooAssembly"),
        access: AssemblyBuilderAccess.Run)
      .DefineDynamicModule("FooModule")
      .DefineType("Foo", TypeAttributes.Class);

    typeBuilder
      .DefineDefaultConstructor(MethodAttributes.Public);

    var method = typeBuilder
      .DefineMethod("SayHello", MethodAttributes.Public);

    var il = method.GetILGenerator();
    il.EmitWriteLine("Hello!");
    il.Emit(OpCodes.Ret);

    return typeBuilder.CreateType();
  }

  static void Main()
  {
    var type = CreateDynamicType();
    dynamic instance = Activator.CreateInstance(type);
    instance.SayHello();
  }
}

Produces the exception: 产生例外:

Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'SayHello' 未处理的异常:Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:'object'不包含'SayHello'的定义

But calls via reflection API perfectly works. 但是通过反射API的调用非常有效。 Any ideas? 有任何想法吗?

dynamic won't resolve members on internal types from different assemblies. dynamic不会解析来自不同程序集的内部类型的成员。
(just like the compiler won't) (就像编译器不会)

Make the type public. 将类型设为公开。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM