C # dynamic + System.Reflection.Emit = don't mix?

Why does the code look 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();
  }
}

      

Throws an exception:

Unhandled Exception: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for "SayHello"

But calls through the reflection API work fine. Any ideas?

+3


source to share


1 answer


dynamic

will not resolve members on internal types from different assemblies.
(just like the compiler won't)



Make the type public.

+9


source







All Articles