I wrote following program in order to understand object constructi开发者_如何学JAVAon and method call in IL Unfortunately it doesn’t print
How are you doing
on the console.
Do you have any idea?
Output of peverify is also given below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection.Emit;
using System.Reflection;
using System.IO;
namespace Research
{
public class Program
{
public static void Main(string[] args)
{
AssemblyName name =
new AssemblyName(Path.GetFileNameWithoutExtension("Hello"));
AssemblyBuilder asmb =
System.AppDomain.CurrentDomain.DefineDynamicAssembly(name,
AssemblyBuilderAccess.Save);
ModuleBuilder modb = asmb.DefineDynamicModule("Hello");
TypeBuilder typeBuilder = modb.DefineType("Bar");
MethodBuilder methb =
typeBuilder.DefineMethod("Me", MethodAttributes.Static,
typeof(void), System.Type.EmptyTypes);
ILGenerator gen = methb.GetILGenerator();
ConstructorInfo cil = typeof(Research.Dog).GetConstructor(new Type[] { });
gen.Emit(OpCodes.Newobj, cil);
gen.Emit(OpCodes.Call, typeof(Research.Dog).GetMethod("Bark"));
gen.Emit(OpCodes.Ret);
}
}
public class Dog
{
public void Bark()
{
Console.WriteLine("How are you doing");
}
}
}
C:\temp\Research\Research\bin\Release>peverify Research.exe
Microsoft (R) .NET Framework PE Verifier. Version 4.0.30319.1 Copyright (c) Microsoft Corporation. All rights reserved.
All Classes and Methods in Research.exe Verified.
C:\temp\Research\Research\bin\Release>
You create a dynamic assembly and then do nothing with it. Why should that print anything? Also, peverify won't help you in any way here, because you're not verifying the assembly you generated, you're verifying just the assembly that's generating it.
You also don't call typeBuilder.CreateType()
, which is necessary and your assembly isn't set to be able to run.
If you use AssemblyBuilderAccess.RunAndSave
and add the following code at the end of the method, it will work (at least it works for me):
var barType = typeBuilder.CreateType();
var meMethod = barType.GetMethod("Me", BindingFlags.Static | BindingFlags.NonPublic);
meMethod.Invoke(null, null);
精彩评论