本文整理汇总了C#中System.Reflection.Emit.DynamicMethod类的典型用法代码示例。如果您正苦于以下问题:C# DynamicMethod类的具体用法?C# DynamicMethod怎么用?C# DynamicMethod使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DynamicMethod类属于System.Reflection.Emit命名空间,在下文中一共展示了DynamicMethod类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateGetField
internal static GenericGetter CreateGetField(Type type, FieldInfo fieldInfo)
{
DynamicMethod dynamicGet = new DynamicMethod("_", typeof(object), new Type[] { typeof(object) }, type);
ILGenerator il = dynamicGet.GetILGenerator();
if (!type.IsClass) // structs
{
var lv = il.DeclareLocal(type);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Unbox_Any, type);
il.Emit(OpCodes.Stloc_0);
il.Emit(OpCodes.Ldloca_S, lv);
il.Emit(OpCodes.Ldfld, fieldInfo);
if (fieldInfo.FieldType.IsValueType)
il.Emit(OpCodes.Box, fieldInfo.FieldType);
}
else
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, fieldInfo);
if (fieldInfo.FieldType.IsValueType)
il.Emit(OpCodes.Box, fieldInfo.FieldType);
}
il.Emit(OpCodes.Ret);
return (GenericGetter)dynamicGet.CreateDelegate(typeof(GenericGetter));
}
示例2: RedisFactory
public RedisFactory(bool saveDynamicAssembly = false)
{
var redisTypes = RedisTypeBuilder.BuildRedisTypes();
if (saveDynamicAssembly)
{
redisTypes.SaveAssembly();
}
// Build CreateRedis dynamic method
var createRedisDynamicMethod = new DynamicMethod("CreateRedis", typeof(IRedis), new[] { typeof(IRedisConnection) });
var redisConstructor = redisTypes.RedisType.GetConstructor(new[] { typeof(IRedisConnection) });
var createRedisGenerator = createRedisDynamicMethod.GetILGenerator();
createRedisGenerator.Emit(OpCodes.Ldarg_0);
createRedisGenerator.Emit(OpCodes.Newobj, redisConstructor);
createRedisGenerator.Emit(OpCodes.Ret);
// Build CreateRedisExec dynamic method
var createRedisPipelineDynamicMethod = new DynamicMethod("CreateRedisPipeline", typeof(IRedisPipeline), new[] { typeof(IRedisConnection), typeof(bool) });
var redisPipelineConstructor = redisTypes.RedisPipelineType.GetConstructor(new[] { typeof(IRedisConnection), typeof(bool) });
var createRedisPipelineGenerator = createRedisPipelineDynamicMethod.GetILGenerator();
createRedisPipelineGenerator.Emit(OpCodes.Ldarg_0);
createRedisPipelineGenerator.Emit(OpCodes.Ldarg_1);
createRedisPipelineGenerator.Emit(OpCodes.Newobj, redisPipelineConstructor);
createRedisPipelineGenerator.Emit(OpCodes.Ret);
// Create delegates from dynamic methods
this.createRedis = (CreateRedisDelegate) createRedisDynamicMethod.CreateDelegate(typeof (CreateRedisDelegate));
this.createRedisPipeline = (CreateRedisPipelineDelegate)createRedisPipelineDynamicMethod.CreateDelegate(typeof(CreateRedisPipelineDelegate));
}
示例3: CreateCreateInstanceMethod
/// <summary>
/// Generates a dynamic method which creates a new instance of <paramref name="type" />
/// when invoked.
/// </summary>
private CreateInstanceInvoker CreateCreateInstanceMethod(System.Type type)
{
if (type.IsInterface || type.IsAbstract)
{
return null;
}
DynamicMethod method = new DynamicMethod(string.Empty, typeof(object), null, type, true);
ILGenerator il = method.GetILGenerator();
if (type.IsValueType)
{
LocalBuilder tmpLocal = il.DeclareLocal(type);
il.Emit(OpCodes.Ldloca, tmpLocal);
il.Emit(OpCodes.Initobj, type);
il.Emit(OpCodes.Ldloc, tmpLocal);
il.Emit(OpCodes.Box, type);
}
else
{
ConstructorInfo constructor = ReflectHelper.GetDefaultConstructor(type);
if (constructor == null)
{
throw new InstantiationException("Object class " + type + " must declare a default (no-argument) constructor", type);
}
il.Emit(OpCodes.Newobj, constructor);
}
il.Emit(OpCodes.Ret);
return (CreateInstanceInvoker)method.CreateDelegate(typeof(CreateInstanceInvoker));
}
示例4: CreateActivator
public Activator CreateActivator(Type type, out List<Type> dependencies)
{
dependencies = new List<Type>();
ConstructorInfo constructorInfo = type.GetConstructors()[0];
ParameterInfo[] parameters = constructorInfo.GetParameters();
var method = new DynamicMethod("CreateInstance", typeof(object), new[] { typeof(object[]) });
ILGenerator generator = method.GetILGenerator();
for (int index = 0; index < parameters.Length; index++)
{
Type parameterType = parameters[index].ParameterType;
dependencies.Add(parameterType);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldc_I4, index);
generator.Emit(OpCodes.Ldelem_Ref);
generator.Emit(parameterType.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, parameterType);
}
generator.Emit(OpCodes.Newobj, constructorInfo);
generator.Emit(OpCodes.Ret);
var activator = method.CreateDelegate(typeof(Activator)) as Activator;
return activator;
}
示例5: GetBindByName
static Action<IDbCommand, bool> GetBindByName(Type commandType)
{
if (commandType == null) return null; // GIGO
Action<IDbCommand, bool> action;
if (Link<Type, Action<IDbCommand, bool>>.TryGet(bindByNameCache, commandType, out action))
{
return action;
}
var prop = commandType.GetProperty("BindByName", BindingFlags.Public | BindingFlags.Instance);
action = null;
ParameterInfo[] indexers;
MethodInfo setter;
if (prop != null && prop.CanWrite && prop.PropertyType == typeof(bool)
&& ((indexers = prop.GetIndexParameters()) == null || indexers.Length == 0)
&& (setter = prop.GetSetMethod()) != null
)
{
var method = new DynamicMethod(commandType.Name + "_BindByName", null, new Type[] { typeof(IDbCommand), typeof(bool) });
var il = method.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Castclass, commandType);
il.Emit(OpCodes.Ldarg_1);
il.EmitCall(OpCodes.Callvirt, setter, null);
il.Emit(OpCodes.Ret);
action = (Action<IDbCommand, bool>)method.CreateDelegate(typeof(Action<IDbCommand, bool>));
}
// cache it
Link<Type, Action<IDbCommand, bool>>.TryAdd(ref bindByNameCache, commandType, ref action);
return action;
}
示例6: CreateGetInsertValues
internal static Func<object, SqlArgument[]> CreateGetInsertValues(IObjectInfo objectInfo)
{
var dynamicMethod = new DynamicMethod(
name: "MicroLite" + objectInfo.ForType.Name + "GetInsertValues",
returnType: typeof(SqlArgument[]),
parameterTypes: new[] { typeof(object) }, // arg_0
m: typeof(ObjectInfo).Module);
var ilGenerator = dynamicMethod.GetILGenerator();
ilGenerator.DeclareLocal(objectInfo.ForType); // loc_0 - {Type} instance;
ilGenerator.DeclareLocal(typeof(SqlArgument[])); // loc_1 - SqlArgument[] sqlArguments;
// instance = ({Type})arg_0;
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit(OpCodes.Castclass, objectInfo.ForType);
ilGenerator.Emit(OpCodes.Stloc_0);
// sqlArguments = new SqlArgument[count];
ilGenerator.EmitEfficientInt(objectInfo.TableInfo.InsertColumnCount);
ilGenerator.Emit(OpCodes.Newarr, typeof(SqlArgument));
ilGenerator.Emit(OpCodes.Stloc_1);
EmitGetPropertyValues(ilGenerator, objectInfo, c => c.AllowInsert);
// return sqlArguments;
ilGenerator.Emit(OpCodes.Ldloc_1);
ilGenerator.Emit(OpCodes.Ret);
var getInsertValues = (Func<object, SqlArgument[]>)dynamicMethod.CreateDelegate(typeof(Func<object, SqlArgument[]>));
return getInsertValues;
}
示例7: DynamicILGenerator
internal unsafe DynamicILGenerator(DynamicMethod method, byte[] methodSignature, int size)
: base(method, size)
{
m_scope = new DynamicScope();
m_methodSigToken = m_scope.GetTokenFor(methodSignature);
}
示例8: CreateFieldGetter
public static GetValueDelegate CreateFieldGetter(FieldInfo field)
{
if (field == null)
throw new ArgumentNullException("field");
DynamicMethod dm = new DynamicMethod("FieldGetter", typeof(object),
new Type[] { typeof(object) },
field.DeclaringType, true);
ILGenerator il = dm.GetILGenerator();
if (!field.IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
EmitCastToReference(il, field.DeclaringType); //to handle struct object
il.Emit(OpCodes.Ldfld, field);
}
else
il.Emit(OpCodes.Ldsfld, field);
if (field.FieldType.IsValueType)
il.Emit(OpCodes.Box, field.FieldType);
il.Emit(OpCodes.Ret);
return (GetValueDelegate)dm.CreateDelegate(typeof(GetValueDelegate));
}
示例9: GetDynamicInstance
private static object GetDynamicInstance(Type type) {
if (typeof (MulticastDelegate).IsAssignableFrom(type)) {
DynamicMethod method = new DynamicMethod("XStreamDynamicDelegate", typeof (void), GetDelegateParameterTypes(type), typeof (object));
ILGenerator generator = method.GetILGenerator();
generator.Emit(OpCodes.Ret);
return method.CreateDelegate(type);
}
if (type.IsSealed)
throw new ConversionException("Impossible to construct type: " + type);
// Check if we already have the type defined
string typeName = prefix + type;
lock (typeMap) {
Type dynamicType = typeMap[typeName] as Type;
if (dynamicType == null) {
TypeBuilder typeBuilder = ModuleBuilder.DefineType(typeName, TypeAttributes.Class | TypeAttributes.NotPublic, type);
ConstructorBuilder cb = typeBuilder.DefineConstructor(MethodAttributes.Private, CallingConventions.Standard, new Type[0]);
cb.GetILGenerator().Emit(OpCodes.Ret);
dynamicType = typeBuilder.CreateType();
typeMap[typeName] = dynamicType;
}
return Activator.CreateInstance(dynamicType, true);
}
}
示例10: GetFiller
//todo: temporary public
public FillingDelegate GetFiller(TypeMappingInfo mapping, Table table)
{
var ct = typeof(object);
// Fill(reader, obj, offset)
Type[] methodArgs2 = { typeof(IDataRecord), ct, typeof(int) };
var method = new DynamicMethod(
"ct",
null,
methodArgs2, typeof(SqlValueMapper));
var generator = method.GetILGenerator();
Type type = mapping.Type;
var i = 0;
foreach(var prop in table.Columns)
{
var navigation = prop as NavigationPropertyMapping;
if (navigation != null)
{
GenerateForNavigationProperty(navigation, type, generator, i);
}
else
{
GenerateForPrimitive(type, prop, generator, i);
}
i++;
}
// return
generator.Emit(OpCodes.Ret);
return (FillingDelegate)method.CreateDelegate(typeof(FillingDelegate));
}
示例11: CreateGetMethod
private static DynamicGetter CreateGetMethod(PropertyInfo propertyInfo, Type type)
{
var getMethod = propertyInfo.GetGetMethod();
if (getMethod == null)
throw new InvalidOperationException(string.Format("Could not retrieve GetMethod for the {0} property of {1} type", propertyInfo.Name, type.FullName));
var arguments = new Type[1]
{
typeof (object)
};
var getterMethod = new DynamicMethod(string.Concat("_Get", propertyInfo.Name, "_"), typeof(object), arguments, propertyInfo.DeclaringType);
var generator = getterMethod.GetILGenerator();
generator.DeclareLocal(typeof(object));
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Castclass, propertyInfo.DeclaringType);
generator.EmitCall(OpCodes.Callvirt, getMethod, null);
if (propertyInfo.PropertyType.IsClass == false)
generator.Emit(OpCodes.Box, propertyInfo.PropertyType);
generator.Emit(OpCodes.Ret);
return (DynamicGetter) getterMethod.CreateDelegate(typeof (DynamicGetter));
}
示例12: GetInstanceCreator
/// <summary>Gets the instance creator delegate that can be use to create instances of the specified type.</summary>
/// <param name="type">The type of the objects we want to create.</param>
/// <returns>A delegate that can be used to create the objects.</returns>
public static FastCreateInstanceHandler GetInstanceCreator(Type type)
{
lock (dictCreator)
{
if (dictCreator.ContainsKey(type)) return (FastCreateInstanceHandler)dictCreator[type];
// generates a dynamic method to generate a FastCreateInstanceHandler delegate
DynamicMethod dynamicMethod = new DynamicMethod(string.Empty, type, new Type[0], typeof(DynamicCalls).Module);
ILGenerator ilGenerator = dynamicMethod.GetILGenerator();
// generates code to create a new object of the specified type using the default constructor
ilGenerator.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes));
// returns the value to the caller
ilGenerator.Emit(OpCodes.Ret);
// converts the DynamicMethod to a FastCreateInstanceHandler delegate to create the object
FastCreateInstanceHandler creator = (FastCreateInstanceHandler)dynamicMethod.CreateDelegate(typeof(FastCreateInstanceHandler));
dictCreator.Add(type, creator);
return creator;
}
}
示例13: CreateCloneWrapper
private static CloneHandler CreateCloneWrapper(Type type)
{
var cloneMethod = new DynamicMethod
(
"NativeClone",
MethodAttributes.Public | MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.Final | MethodAttributes.NewSlot,
CallingConventions.Standard,
typeof(IntPtr), new Type[] { type },
type, false
);
var ilGenerator = cloneMethod.GetILGenerator();
ilGenerator.Emit(OpCodes.Ldarg_0); // Step 1: Push the object to clone on the stack
// Just to be clean, don't suppose ICloneable only has one member…
var cloneableInterfaceMap = type.GetInterfaceMap(typeof(ICloneable));
for (int i = 0; i < cloneableInterfaceMap.InterfaceMethods.Length; i++)
if (cloneableInterfaceMap.InterfaceMethods[i].Name == "Clone")
{
ilGenerator.Emit(OpCodes.Call, cloneableInterfaceMap.TargetMethods[i]); // Step 2: clone it
goto CloneMethodFound; // Finish the job once we found the Clone method (which should always be found)
}
throw new InvalidOperationException(); // This line should never be reached
CloneMethodFound:
ilGenerator.Emit(OpCodes.Isinst, type); // Step 3: Cast it to the correct type
var nativePointerProperty = type.GetProperty
(
"NativePointer",
BindingFlags.NonPublic | BindingFlags.Instance, Type.DefaultBinder,
typeof(IntPtr), Type.EmptyTypes, null
);
ilGenerator.Emit(OpCodes.Call, nativePointerProperty.GetGetMethod(true)); // Step 4: Get the native pointer
ilGenerator.Emit(OpCodes.Ret); // Step 5: Return the value
return cloneMethod.CreateDelegate(typeof(CloneHandler)) as CloneHandler;
}
示例14: TestCall2
public void TestCall2()
{
var parameters = new[] { typeof(int), typeof(int) };
var dm = new DynamicMethod("soma", typeof(int), parameters);
var gen = dm.GetILGenerator();
gen.DeclareLocal (typeof(Math));
var ctor = typeof(Math).GetConstructors () [0];
gen.Emit (OpCodes.Newobj, ctor);
gen.Emit (OpCodes.Stloc, 0);
gen.Emit (OpCodes.Ldobj, 0);
//gen.Emit(OpCodes.Ldarg_0);
//gen.Emit(OpCodes.Ldarg_1);
//var soma = GetType ().GetMethod ("Soma");
//gen.EmitCall (OpCodes.Callvirt, soma, new Type[] { });
gen.Emit (OpCodes.Ldc_I4, 2);
gen.Emit(OpCodes.Ret);
var result = dm.Invoke(null, new object[] { 1, 1 });
//var func = (Func<int, int, int>)dm.CreateDelegate(typeof(Func<int, int, int>));
Assert.AreEqual (2, result);
}
示例15: CreateCreateInstanceMethod
private static CreateInstanceInvoker CreateCreateInstanceMethod(Type type)
{
if (type.IsInterface || type.IsAbstract)
return null;
DynamicMethod method = new DynamicMethod(string.Empty, typeof (object), null, type, true);
ILGenerator il = method.GetILGenerator();
if (type.IsValueType)
{
LocalBuilder tmpLocal = il.DeclareLocal(type);
il.Emit(OpCodes.Ldloca, tmpLocal);
il.Emit(OpCodes.Initobj, type);
il.Emit(OpCodes.Ldloc, tmpLocal);
il.Emit(OpCodes.Box, type);
}
else
{
ConstructorInfo constructor = type.GetConstructor(AnyVisibilityInstance, null, CallingConventions.HasThis, NoClasses, null);
if (constructor == null)
throw new ApplicationException("Object class " + type + " must declare a default (no-argument) constructor");
il.Emit(OpCodes.Newobj, constructor);
}
il.Emit(OpCodes.Ret);
return (CreateInstanceInvoker) method.CreateDelegate(typeof (CreateInstanceInvoker));
}