Dynamic Assemblies and Methods
I've programmed .NET and C# for years now, but have only recently encountered the DynamicMethod
type along with the concept of a Dynamic Assembly within the context of reflection. They seem to always be used within IL (runtime code) generation.
Unfortunately MSDN does an extraordinarily poor job of defining what a dynamic assembly/method actuallty is and also what they should be used for. Could anyoen enlighten me here please? Are there anything to do with the DLR? How are they different to static (normal) generation of assemblies and methods at runtime? What should I know about how and when to use them?
DynamicMethod are used to create methods without any new assembly. They also can be created for a class, so you can access it's private members. Finally, the DynamicMethod class will build a delegate you can use to execute the method. For example, in order to access a private field:
var d = new DynamicMethod("my_dynamic_get_" + field.Name, typeof(object), new[] { typeof(object) }, type, true);
var il = d.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, field);
if (field.FieldType.IsValueType)
il.Emit(OpCodes.Box, field.FieldType);
else
il.Emit(OpCodes.Castclass, typeof(object));
il.Emit(OpCodes.Ret);
var @delegate = (Func<object, object>)d.CreateDelegate(typeof(Func<object, object>));
Hope it helps.
链接地址: http://www.djcxy.com/p/56830.html上一篇: 保存时,django admin重定向到错误的端口
下一篇: 动态装配和方法