Pergunta

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?

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top