Tag: ilgenerator

IL的generics?

是否可以在IL Generator中使用generics? DynamicMethod method = new DynamicMethod( “GetStuff”, typeof(int), new Type[] { typeof(object) }); ILGenerator il = method.GetILGenerator(); … etc

ILGenerator周围有一个很好的包装器吗?

我现在使用System.Reflection.Emit一段时间了,发现它(谁没有?)像容易出错一样痛苦。 你知道IL Generator周围是否有一个好的包装器,我可以依赖它以比直接使用SRE更安全,更容易的方式发出IL吗? 编辑: 我知道操纵表达树比直接发射IL更容易和更安全,但它们现在也有一些限制。 我不能创建代码块,使用循环,声明和使用几个本地,等等。我们需要等到.NET 4出来:) 而且,我正在处理一个已经依赖于SRE的代码库。 显然,ILGenerator会做我需要的一切。 但是在操纵它时我会感激更多的帮助。 当我指的是ILGenerator包装器时,它仍处于相当低的水平,我想到的东西可以提供如下方法: // Performs a virtual or direct call on the method, depending if it is a // virtual or a static one. Call(MethodInfo methodInfo) // Pushes the default value of the type on the stack, then emit // the Ret opcode. ReturnDefault(Type type) // Test […]

动态创建基类的类型和调用构造函数

我需要动态创建一个类。 大多数工作正常,但我坚持生成构造函数。 AssemblyBuilder _assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName(“MyBuilder”), AssemblyBuilderAccess.Run); ModuleBuilder _moduleBuilder = _assemblyBuilder.DefineDynamicModule(“MyModule”); public static object GetInstance(this TSource source, string eventName) where TSource : class { var typeName = “MyTypeName”; var typeBuilder = _moduleBuilder.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public); // create type like class MyClass : GenericType var baseNotGenericType = typeof(GenericType); var baseType = baseNotGenericType.MakeGenericType(typeBuilder, typeof(TSource), typeof(TEventArgs)); typeBuilder.SetParent(baseType); […]

动态对象属性populator(无reflection)

我想在不使用reflection的情况下填充对象的属性,其方式类似于CodeProject上的DynamicBuilder 。 CodeProject示例是为使用DataReader或DataRecord填充实体而定制的。 我在几个DAL中使用它以达到很好的效果。 现在我想修改它以使用字典或其他数据无关的对象,以便我可以在非DAL代码中使用它 – 我目前使用reflection。 我对OpCodes和IL几乎一无所知。 我只知道它运作良好,比reflection更快。 我试图修改CodeProject示例,由于我对IL的无知,我已经陷入两行。 其中一个处理dbnulls,我很确定我可以丢失它,但我不知道它之前和之后的行是否相关以及它们中的哪一个也需要去。 另一方面,我认为,是之前从数据线中取出价值的,现在需要将其从字典中拉出来。 我想我可以用“property.Value”替换“getValueMethod”,但我不确定。 我也愿意采用替代/更好的方法来剥皮这只猫。 这是迄今为止的代码(注释掉的行是我坚持的): using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; public class Populator { private delegate T Load(Dictionary properties); private Load _handler; private Populator() { } public T Build(Dictionary properties) { return _handler(properties); } public static Populator CreateBuilder(Dictionary properties) { //private static […]

如何使用IL改变盒装结构

想象一下,我们有一个可变的struct (是的,不要开始): public struct MutableStruct { public int Foo { get; set; } public override string ToString() { return Foo.ToString(); } } 使用reflection,我们可以获取此struct的盒装实例并在框内变异: // this is basically what we want to emulate object obj = new MutableStruct { Foo = 123 }; obj.GetType().GetProperty(“Foo”).SetValue(obj, 456); System.Console.WriteLine(obj); // “456” 我想做的是写一些可以做到这一点的IL – 但速度更快。 我是一个元编程迷; p 取消任何一个值并使用常规IL来改变值是微不足道的 – 但是你不能只是在之后调用它,因为这将创建一个不同的框。 […]