当前位置: 首页>>代码示例>>C#>>正文


C# DynamicMethod.GetILGenerator方法代码示例

本文整理汇总了C#中System.Reflection.Emit.DynamicMethod.GetILGenerator方法的典型用法代码示例。如果您正苦于以下问题:C# DynamicMethod.GetILGenerator方法的具体用法?C# DynamicMethod.GetILGenerator怎么用?C# DynamicMethod.GetILGenerator使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Reflection.Emit.DynamicMethod的用法示例。


在下文中一共展示了DynamicMethod.GetILGenerator方法的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));
        }
开发者ID:gustafsonk,项目名称:TFS-Treemap,代码行数:29,代码来源:Reflection.cs

示例2: DelegateFieldSetAccessor

                 /// <summary>
        /// Initializes a new instance of the <see cref="DelegateFieldSetAccessor"/> class
        /// for field get access via DynamicMethod.
        /// </summary>
        /// <param name="targetObjectType">Type of the target object.</param>
        /// <param name="fieldName">Name of the field.</param>
        public DelegateFieldSetAccessor(Type targetObjectType, string fieldName)
        {
           // this.targetType = targetObjectType;
            _fieldName = fieldName;

            FieldInfo fieldInfo = targetObjectType.GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);

            // Make sure the field exists
            if (fieldInfo == null)
            {
                throw new NotSupportedException(
                    string.Format("Field \"{0}\" does not exist for type "
                    + "{1}.", fieldName, targetObjectType));
            }
                     _fieldType = fieldInfo.FieldType;
                     nullInternal = GetNullInternal(_fieldType);

                     // Emit the IL for set access. 
                     DynamicMethod dynamicMethodSet = new DynamicMethod("SetImplementation", null, new Type[] { typeof(object), typeof(object) }, GetType().Module, false);
                     ILGenerator ilgen = dynamicMethodSet.GetILGenerator();

                     ilgen = dynamicMethodSet.GetILGenerator();

                     ilgen.Emit(OpCodes.Ldarg_0);
                     ilgen.Emit(OpCodes.Ldarg_1);
                     UnboxIfNeeded(fieldInfo.FieldType, ilgen);
                     ilgen.Emit(OpCodes.Stfld, fieldInfo);
                     ilgen.Emit(OpCodes.Ret);

                     _set = (SetValue)dynamicMethodSet.CreateDelegate(typeof(SetValue));
        }
开发者ID:techvenky,项目名称:mybatisnet,代码行数:37,代码来源:DelegateSetFieldAccessor.cs

示例3: GenerateDelegate

        private static PropertyMapper GenerateDelegate(Type sourceType, Type targetType, bool ignoreMappings)
        {
            var method = new DynamicMethod("Map_" + sourceType.FullName + "_" + targetType.FullName, null, new[] { typeof(object), typeof(object) });
            var il = method.GetILGenerator();

            var sourceProperties = Reflector.GetAllProperties(sourceType);
            var targetProperties = Reflector.GetAllProperties(targetType);

            var entityMap = MappingFactory.GetEntityMap(targetType);

            var matches = sourceProperties.CrossJoin(targetProperties).Where(t => t.Item2.Name == MappingFactory.GetPropertyOrColumnName(t.Item3, ignoreMappings, entityMap, false)
                                                                                    && t.Item2.PropertyType == t.Item3.PropertyType
                                                                                    && t.Item2.PropertyType.IsPublic
                                                                                    && t.Item3.PropertyType.IsPublic
                                                                                    //&& (t.Item3.PropertyType.IsValueType || t.Item3.PropertyType == typeof(string))
                                                                                    && t.Item2.CanRead && t.Item3.CanWrite);

            foreach (var match in matches)
            {
                il.Emit(OpCodes.Ldarg_1);
                il.EmitCastToReference(targetType);
                il.Emit(OpCodes.Ldarg_0);
                il.EmitCastToReference(sourceType);
                il.Emit(OpCodes.Callvirt, match.Item2.GetGetMethod());
                il.Emit(OpCodes.Callvirt, match.Item3.GetSetMethod());
            }
            il.Emit(OpCodes.Ret);

            var mapper = (PropertyMapper)method.CreateDelegate(typeof(PropertyMapper));
            return mapper;
        }
开发者ID:ulrakhma,项目名称:Nemo,代码行数:31,代码来源:Mapper.cs

示例4: CreateGetMethod

        /// <summary>
        /// Creates a dynamic getter for the property
        /// </summary>
        /// <param name="propertyInfo"></param>
        /// <returns></returns>
        public static GenericGetter CreateGetMethod(PropertyInfo propertyInfo)
        {
            /*
             * If there's no getter return null
             */
            MethodInfo getMethod = propertyInfo.GetGetMethod();
            if (getMethod == null)
                return null;

            /*
             * Create the dynamic method
             */
            Type[] arguments = new Type[1];
            arguments[0] = typeof(object);

            DynamicMethod getter = new DynamicMethod(
                String.Concat("_Get", propertyInfo.Name, "_"),
                typeof(object), arguments, propertyInfo.DeclaringType,false);

            ILGenerator generator = getter.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)
                generator.Emit(OpCodes.Box, propertyInfo.PropertyType);

            generator.Emit(OpCodes.Ret);

            /*
             * Create the delegate and return it
             */
            return (GenericGetter)getter.CreateDelegate(typeof(GenericGetter));
        }
开发者ID:Jiannan,项目名称:PlainTextSerializer,代码行数:40,代码来源:ReflectonHelper.cs

示例5: GenerateMethodBody

		private void GenerateMethodBody(DynamicMethod dynamicMethod) {
			var ilGenerator = dynamicMethod.GetILGenerator();
			ilGenerator.Emit(OpCodes.Ldarg_0); // Load templateControl argument onto stack
			ilGenerator.Emit(OpCodes.Ldarg_1); // Load virtualPath argument onto stack
			ilGenerator.Emit(OpCodes.Call, invoker); // Invoke LoadControlInvoker with the loaded two arguments
			ilGenerator.Emit(OpCodes.Ret); // End method
		}
开发者ID:aelveborn,项目名称:njupiter,代码行数:7,代码来源:ControlLoader.cs

示例6: 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;
 }
开发者ID:namman,项目名称:ServiceStack,代码行数:30,代码来源:ProfiledDbCommand.cs

示例7: BehaviorModel

        public BehaviorModel()
        {
            var modelType = GetType();
            if (!s_data.TryGetValue(modelType, out m_data))
            {
                lock (s_data)
                {
                    if (!s_data.TryGetValue(modelType, out m_data))
                    {
                        m_data = new BehaviorModelData
                        {
                            BhvModelAttr = modelType.GetAttribute<BehaviorModelAttribute>()
                        };
                        var bhvType = m_data.BhvModelAttr != null
                                      ? m_data.BhvModelAttr.BehaviorType
                                      : SupplementBehaviorType; // virtual function call to get the most derived value

                        var dynMethod = new DynamicMethod("DM$OBJ_FACTORY_" + bhvType.FullName, bhvType, null, bhvType);
                        var ilGen = dynMethod.GetILGenerator();
                        ilGen.Emit(OpCodes.Newobj, bhvType.GetConstructor(Type.EmptyTypes));
                        ilGen.Emit(OpCodes.Ret);

                        m_data.BehaviorType = bhvType;
                        m_data.BhvFactory = (Func<IBehavior>)dynMethod.CreateDelegate(typeof(Func<IBehavior>));
                        m_data.IsBehaviorStatic = BehaviorModel.GetIsBehaviorStatic(bhvType);
                        s_data.Add(modelType, m_data);
                    }
                }
            }

            m_name = null;
        }
开发者ID:galaxyyao,项目名称:TouhouGrave,代码行数:32,代码来源:BehaviorModel.cs

示例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));
        }
开发者ID:bluexray,项目名称:TarFramework,代码行数:29,代码来源:DynamicMethodEmit.cs

示例9: 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;
        }
开发者ID:TrevorPilley,项目名称:MicroLite,代码行数:33,代码来源:DelegateFactory.cs

示例10: 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));
		}
开发者ID:GorelH,项目名称:ravendb,代码行数:27,代码来源:PropertyAccessor.cs

示例11: 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));
        }
开发者ID:Rattlemouse,项目名称:PTORMPrototype,代码行数:33,代码来源:SqlValueMapper.cs

示例12: 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;
        }
开发者ID:nagyist,项目名称:monoxide,代码行数:34,代码来源:CloneFactory.cs

示例13: 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;
            }
        }
开发者ID:sndnvaps,项目名称:easy4net,代码行数:28,代码来源:DynamicCalls.cs

示例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);
		}          
开发者ID:santosh-mnrec,项目名称:NPortugol2,代码行数:31,代码来源:Lab.cs

示例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));
        }
开发者ID:KevM,项目名称:Magnum,代码行数:30,代码来源:SerializationOptimizer.cs


注:本文中的System.Reflection.Emit.DynamicMethod.GetILGenerator方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。