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


C# DynamicMethod.DefineParameter方法代码示例

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


在下文中一共展示了DynamicMethod.DefineParameter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: GenerateDynamicDeserializerStub

        static DynamicMethod GenerateDynamicDeserializerStub(Type type) {
            var dm = new DynamicMethod("Deserialize", null,
                new Type[] { typeof(Stream), type.MakeByRefType() },
                typeof(Serializer), true);
            dm.DefineParameter(1, ParameterAttributes.None, "stream");
            dm.DefineParameter(2, ParameterAttributes.Out, "value");

            return dm;
        }
开发者ID:pczy,项目名称:Pub.Class,代码行数:9,代码来源:DeserializerStub.cs

示例2: CreateDynamicAssembly

 private static void CreateDynamicAssembly()
 {
     new SecurityPermission(SecurityPermissionFlag.ControlEvidence).Assert();
     Type[] types = new Type[] { typeof(Type), typeof(Type), typeof(string) };
     MethodInfo methodInfo = typeof(Delegate).GetMethod("CreateDelegate", types);
     DynamicMethod method = new DynamicMethod("CreateDelegate", typeof(Delegate), types);
     method.DefineParameter(1, ParameterAttributes.In, "delegateType");
     method.DefineParameter(2, ParameterAttributes.In, "targetType");
     method.DefineParameter(3, ParameterAttributes.In, "methodName");
     ILGenerator iLGenerator = method.GetILGenerator(5);
     iLGenerator.Emit(OpCodes.Ldarg_0);
     iLGenerator.Emit(OpCodes.Ldarg_1);
     iLGenerator.Emit(OpCodes.Ldarg_2);
     iLGenerator.EmitCall(OpCodes.Call, methodInfo, null);
     iLGenerator.Emit(OpCodes.Ret);
     s_CreateDelegate1 = (CreateDelegate1Delegate) method.CreateDelegate(typeof(CreateDelegate1Delegate));
     types = new Type[] { typeof(Type), typeof(object), typeof(string) };
     methodInfo = typeof(Delegate).GetMethod("CreateDelegate", types);
     method = new DynamicMethod("CreateDelegate", typeof(Delegate), types);
     method.DefineParameter(1, ParameterAttributes.In, "delegateType");
     method.DefineParameter(2, ParameterAttributes.In, "target");
     method.DefineParameter(3, ParameterAttributes.In, "methodName");
     iLGenerator = method.GetILGenerator(5);
     iLGenerator.Emit(OpCodes.Ldarg_0);
     iLGenerator.Emit(OpCodes.Ldarg_1);
     iLGenerator.Emit(OpCodes.Ldarg_2);
     iLGenerator.EmitCall(OpCodes.Call, methodInfo, null);
     iLGenerator.Emit(OpCodes.Ret);
     s_CreateDelegate2 = (CreateDelegate2Delegate) method.CreateDelegate(typeof(CreateDelegate2Delegate));
     types = new Type[] { typeof(Type), typeof(object[]) };
     methodInfo = typeof(Activator).GetMethod("CreateInstance", types);
     method = new DynamicMethod("CreateInstance", typeof(object), types);
     method.DefineParameter(1, ParameterAttributes.In, "type");
     method.DefineParameter(2, ParameterAttributes.In, "arguments");
     iLGenerator = method.GetILGenerator(4);
     iLGenerator.Emit(OpCodes.Ldarg_0);
     iLGenerator.Emit(OpCodes.Ldarg_1);
     iLGenerator.EmitCall(OpCodes.Call, methodInfo, null);
     iLGenerator.Emit(OpCodes.Ret);
     s_CreateInstance = (CreateInstanceDelegate) method.CreateDelegate(typeof(CreateInstanceDelegate));
     types = new Type[] { typeof(object), typeof(object[]) };
     Type[] parameterTypes = new Type[] { typeof(MethodInfo), typeof(object), typeof(object[]) };
     methodInfo = typeof(MethodInfo).GetMethod("Invoke", types);
     method = new DynamicMethod("InvokeMethod", typeof(object), parameterTypes);
     method.DefineParameter(1, ParameterAttributes.In, "method");
     method.DefineParameter(2, ParameterAttributes.In, "instance");
     method.DefineParameter(3, ParameterAttributes.In, "args");
     iLGenerator = method.GetILGenerator(5);
     iLGenerator.Emit(OpCodes.Ldarg_0);
     iLGenerator.Emit(OpCodes.Ldarg_1);
     iLGenerator.Emit(OpCodes.Ldarg_2);
     iLGenerator.EmitCall(OpCodes.Callvirt, methodInfo, null);
     iLGenerator.Emit(OpCodes.Ret);
     s_InvokeMethod = (InvokeMethodDelegate) method.CreateDelegate(typeof(InvokeMethodDelegate));
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:55,代码来源:SafeReflectionInvoker.cs

示例3: GenerateDynamicSerializerStub

        public static DynamicMethod GenerateDynamicSerializerStub(Type type)
        {
            var dm = new DynamicMethod("Serialize", null,
                new Type[] { typeof(IoBuffer), type },
                typeof(Serializer), true);

            dm.DefineParameter(1, ParameterAttributes.None, "stream");
            dm.DefineParameter(2, ParameterAttributes.None, "value");

            return dm;
        }
开发者ID:Egipto87,项目名称:DOOP.ec,代码行数:11,代码来源:SerializerCodegen.cs

示例4: GenerateDynamicDeserializeInvokerStub

        public static DynamicMethod GenerateDynamicDeserializeInvokerStub()
        {
            var dm = new DynamicMethod(string.Empty, null,
                new Type[] { typeof(Stream), typeof(object).MakeByRefType(), typeof(ObjectList) },
                typeof(Serializer), true);
            dm.DefineParameter(1, ParameterAttributes.None, "stream");
            dm.DefineParameter(2, ParameterAttributes.Out, "value");
            dm.DefineParameter(3, ParameterAttributes.None, "objList");

            return dm;
        }
开发者ID:smalinin,项目名称:netserializer,代码行数:11,代码来源:DeserializerCodegen.cs

示例5: CreateCompatibleListener

        private Delegate CreateCompatibleListener(EventInfo eventInfo)
        {
            string methodName = eventInfo.Name + "_handler_";

            var delegateType = eventInfo.EventHandlerType;

            var invokeMethod = delegateType.GetMethod("Invoke");

            if (invokeMethod.ReturnType != typeof(void))
                throw new NotSupportedException();

            var delegateParameters = invokeMethod.GetParameters();

            var args = new List<Type> {typeof (EventListener)};
            args.AddRange(delegateParameters.Select(p=>p.ParameterType));

            var dm = new DynamicMethod(methodName,
                typeof (void),
                args.ToArray(),
                typeof(EventListener));

            var generator = dm.GetILGenerator(256);
            generator.DeclareLocal(typeof (Dictionary<string, object>));
            
            generator.Emit(OpCodes.Newobj, _dictionaryCto);
            generator.Emit(OpCodes.Stloc_0);

            var savedArgsField = GetType().GetField("_savedArgs", BindingFlags.Instance | BindingFlags.NonPublic);
            Debug.Assert(savedArgsField != null);

            // add the arguments received to the dictionary
            for (var idx = 0; idx < delegateParameters.Length; idx++)
            {
                var parameter = delegateParameters[idx];

                dm.DefineParameter(idx + 2, ParameterAttributes.In, parameter.Name);

                generator.Emit(OpCodes.Ldloc_0);
                generator.Emit(OpCodes.Ldstr, parameter.Name);
                generator.Emit(OpCodes.Ldarg, idx + 1);

                if (parameter.ParameterType.IsValueType)
                {
                    generator.Emit(OpCodes.Box, parameter.ParameterType);
                }
                generator.Emit(OpCodes.Callvirt, _dictionarySetItemMethod);
            }

            // add the dictionary to the list
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldfld, savedArgsField);
            generator.Emit(OpCodes.Ldloc_0);
            generator.Emit(OpCodes.Callvirt, _listAddMethod);
            
            generator.Emit(OpCodes.Ret);

            return dm.CreateDelegate(delegateType, this);
        }
开发者ID:lishxi,项目名称:_SharpMap,代码行数:58,代码来源:EventListener.cs

示例6: GetNewTileFromMethod

		/// <summary>
		/// Creates an ITile instance using the defaul Terraria.Tile constructor.
		/// 
		/// This cannot be performed at compile time using the OTAPI solution as
		/// Terraria.Tile does not implement ITile at compile time.
		/// </summary>
		/// <returns>ITile instance</returns>
		private static Func<OTAPI.Tile.ITile, OTAPI.Tile.ITile> GetNewTileFromMethod()
		{
			var dm = new DynamicMethod("GetTileFromCollection", typeof(OTAPI.Tile.ITile), new[]
			{
				typeof(OTAPI.Tile.ITile)
			});

			dm.DefineParameter(0, System.Reflection.ParameterAttributes.In, "copy");
			var processor = dm.GetILGenerator();

			processor.Emit(OpCodes.Ldarg_0);
			processor.Emit(OpCodes.Newobj, typeof(global::Terraria.Tile).GetConstructors().Single(x => x.GetParameters().Length == 1));
			processor.Emit(OpCodes.Ret);

			return (Func<OTAPI.Tile.ITile, OTAPI.Tile.ITile>)dm.CreateDelegate(typeof(Func<OTAPI.Tile.ITile, OTAPI.Tile.ITile>));
		}
开发者ID:DeathCradle,项目名称:Open-Terraria-API,代码行数:23,代码来源:Collection.cs

示例7: Wrap

        /// <summary>
        /// Wrap the parsed the function into a delegate of the specified type. The delegate must accept 
        /// the parameters defined in the parameters collection. The order of parameters is respected as defined
        /// in parameters collection.
        /// <br/>
        /// The function must accept a dictionary of strings and doubles as input. The values passed to the 
        /// wrapping function will be passed to the function using the dictionary. The keys in the dictionary
        /// are the names of the parameters of the wrapping function.
        /// </summary>
        /// <param name="parameters">The required parameters of the wrapping function delegate.</param>
        /// <param name="function">The function that must be wrapped.</param>
        /// <returns>A delegate instance of the required type.</returns>
        public Delegate Wrap(IEnumerable<Jace.Execution.ParameterInfo> parameters, 
            Func<Dictionary<string, double>, double> function)
        {
            Jace.Execution.ParameterInfo[] parameterArray = parameters.ToArray();

            Type[] parameterTypes = GetParameterTypes(parameterArray);

            Type delegateType = GetDelegateType(parameterArray);

            DynamicMethod method = new DynamicMethod("FuncWrapperMethod", typeof(double),
                parameterTypes, typeof(FuncAdapterArguments));

            ILGenerator generator = method.GetILGenerator();

            GenerateMethodBody(generator, parameterArray, function);

            for (int i = 0; i < parameterArray.Length; i++)
            {
                Jace.Execution.ParameterInfo parameter = parameterArray[i];
                method.DefineParameter((i + 1), ParameterAttributes.In, parameter.Name);
            }

            return method.CreateDelegate(delegateType, new FuncAdapterArguments(function));
        }
开发者ID:plurby,项目名称:Jace,代码行数:36,代码来源:FuncAdapter.cs

示例8: DynamicCreateMethod


//.........这里部分代码省略.........
            Console.WriteLine("\r\nMethod Attributes: {0}", hello.Attributes);

            // Display the calling convention of the dynamic method, set when the dynamic method was created.
            Console.WriteLine("\r\nCalling convention: {0}", hello.CallingConvention);

            // Display the declaring type, which is always null for dynamic methods.
            if (hello.DeclaringType == null)
                Console.WriteLine("\r\nDeclaringType is always null for dynamic methods.");
            else
                Console.WriteLine("DeclaringType: {0}", hello.DeclaringType);

            // Display the default value for InitLocals.
            if (hello.InitLocals)
                Console.Write("\r\nThis method contains verifiable code.");
            else
                Console.Write("\r\nThis method contains unverifiable code.");
            Console.WriteLine(" (InitLocals = {0})", hello.InitLocals);

            // Display the module specified when the dynamic method was created.
            Console.WriteLine("\r\nModule: {0}", hello.Module);

            // Display the name specified when the dynamic method was created.
            // Note that the name can be blank.
            Console.WriteLine("\r\nName: {0}", hello.Name);

            // For dynamic methods, the reflected type is always null.
            if (hello.ReflectedType == null)
                Console.WriteLine("\r\nReflectedType is null.");
            else
                Console.WriteLine("\r\nReflectedType: {0}", hello.ReflectedType);
            if (hello.ReturnParameter == null)
                Console.WriteLine("\r\nMethod has no return parameter.");
            else
                Console.WriteLine("\r\nReturn parameter: {0}", hello.ReturnParameter);
            // If the method has no return type, ReturnType is System.Void.
            Console.WriteLine("\r\nReturn type: {0}", hello.ReturnType);

            // ReturnTypeCustomAttributes returns an ICustomeAttributeProvider
            // that can be used to enumerate the custom attributes of the
            // return value. At present, there is no way to set such custom
            // attributes, so the list is empty.
            if (hello.ReturnType == typeof(void))
                Console.WriteLine("The method has no return type.");
            else
            {
                ICustomAttributeProvider caProvider = hello.ReturnTypeCustomAttributes;
                object[] returnAttributes = caProvider.GetCustomAttributes(true);
                if (returnAttributes.Length == 0)
                    Console.WriteLine("\r\nThe return type has no custom attributes.");
                else
                {
                    Console.WriteLine("\r\nThe return type has the following custom attributes:");
                    foreach (object attr in returnAttributes)
                    {
                        Console.WriteLine("\t{0}", attr.ToString());
                    }
                }
            }

            Console.WriteLine("\r\nToString: {0}", hello.ToString());

            // Add parameter information to the dynamic method. (This is not
            // necessary, but can be useful for debugging.) For each parameter,
            // identified by position, supply the parameter attributes and a
            // parameter name.
            ParameterBuilder parameter1 = hello.DefineParameter(1,ParameterAttributes.In,"message");
            ParameterBuilder parameter2 = hello.DefineParameter(2,ParameterAttributes.In,"valueToReturn");

            // Display parameter information.
            ParameterInfo[] parameters = hello.GetParameters();
            Console.WriteLine("\r\nParameters: name, type, ParameterAttributes");
            foreach (ParameterInfo p in parameters)
            {
                Console.WriteLine("\t{0}, {1}, {2}",
                    p.Name, p.ParameterType, p.Attributes);
            }

            // Create a delegate that represents the dynamic method.
            //This action completes the method, and any further attempts to change the method will cause an exception.
            HelloDelegate hi = (HelloDelegate)hello.CreateDelegate(typeof(HelloDelegate));

            // Use the delegate to execute the dynamic method.
            Console.WriteLine("\r\nUse the delegate to execute the dynamic method:");
            int retval = hi("\r\nHello, World!", 42);
            Console.WriteLine("Invoking delegate hi(\"Hello, World!\", 42) returned: " + retval);

            // Execute it again, with different arguments.
            retval = hi("\r\nHi, Mom!", 5280);
            Console.WriteLine("Invoking delegate hi(\"Hi, Mom!\", 5280) returned: " + retval);

            Console.WriteLine("\r\nUse the Invoke method to execute the dynamic method:");
            // Create an array of arguments to use with the Invoke method.
            object[] invokeArgs = { "\r\nHello, World!", 42 };
            // Invoke the dynamic method using the arguments. This is much
            // slower than using the delegate, because you must create an
            // array to contain the arguments, and value-type arguments
            // must be boxed.
            object objRet = hello.Invoke(null, BindingFlags.ExactBinding, null, invokeArgs, new System.Globalization.CultureInfo("en-us"));
            Console.WriteLine("hello.Invoke returned: " + objRet);
        }
开发者ID:keily,项目名称:DotNetBasicStudy,代码行数:101,代码来源:Program.cs

示例9: CreateInvokeDelegate

        private static CommandInvocationDelegate CreateInvokeDelegate(MethodInfo targetMethod)
        {
            var method = new DynamicMethod("CommandCache.Invoke", typeof(void), new [] { typeof(object), typeof(object) }, true);

            method.DefineParameter(1, ParameterAttributes.None, "target");
            method.DefineParameter(2, ParameterAttributes.None, "sender");

            var ilGenerator = method.GetILGenerator();

            ilGenerator.Emit(OpCodes.Ldarg_0);
            ilGenerator.Emit(OpCodes.Isinst, targetMethod.DeclaringType);
            ilGenerator.Emit(OpCodes.Ldarg_1);
            ilGenerator.Emit(OpCodes.Tailcall);
            ilGenerator.Emit(OpCodes.Callvirt, targetMethod); // callvirt will check for null references
            ilGenerator.Emit(OpCodes.Ret);

            return method.CreateDelegate(typeof(CommandInvocationDelegate)) as CommandInvocationDelegate;
        }
开发者ID:nagyist,项目名称:monoxide,代码行数:18,代码来源:CommandCache.cs

示例10: GenerateDynamic

        static Dictionary<Type, TypeData> GenerateDynamic(Type[] types, Dictionary<Type, TypeData> typeMap)
        {
            Dictionary<Type, TypeData> _map = GenerateTypeData(types);
            Dictionary<Type, TypeData> map = typeMap.Concat(_map).ToDictionary(kvp => kvp.Key, kvp => kvp.Value);

            var nonStaticTypes = map.Where(kvp => kvp.Value.IsDynamic).Select(kvp => kvp.Key);

            /* generate stubs */
            foreach (var type in nonStaticTypes)
            {
                var s_dm = SerializerCodegen.GenerateDynamicSerializerStub(type);
                var typeData = map[type];
                typeData.WriterMethodInfo = s_dm;
                typeData.WriterILGen = s_dm.GetILGenerator();

                var d_dm = DeserializerCodegen.GenerateDynamicDeserializerStub(type);
                typeData.ReaderMethodInfo = d_dm;
                typeData.ReaderILGen = d_dm.GetILGenerator();
            }

            #if GENERATE_SWITCH
            var serializerSwitchMethod = new DynamicMethod("SerializerSwitch", null,
                new Type[] { typeof(Stream), typeof(object), typeof(ObjectList) },
                typeof(Serializer), true);
            serializerSwitchMethod.DefineParameter(1, ParameterAttributes.None, "stream");
            serializerSwitchMethod.DefineParameter(2, ParameterAttributes.None, "value");
            serializerSwitchMethod.DefineParameter(3, ParameterAttributes.None, "objList");
            var serializerSwitchMethodInfo = serializerSwitchMethod;

            var deserializerSwitchMethod = new DynamicMethod("DeserializerSwitch", null,
                new Type[] { typeof(Stream), typeof(object).MakeByRefType(), typeof(ObjectList) },
                typeof(Serializer), true);
            deserializerSwitchMethod.DefineParameter(1, ParameterAttributes.None, "stream");
            deserializerSwitchMethod.DefineParameter(2, ParameterAttributes.Out, "value");
            deserializerSwitchMethod.DefineParameter(3, ParameterAttributes.Out, "objList");
            var deserializerSwitchMethodInfo = deserializerSwitchMethod;

            var ctx = new CodeGenContext(map, serializerSwitchMethodInfo, deserializerSwitchMethodInfo);
            #else
            var ctx = new CodeGenContext(map);
            #endif

            /* generate bodies */
            foreach (var type in nonStaticTypes)
            {
                SerializerCodegen.GenerateSerializerBody(ctx, type, map[type].WriterILGen);
                DeserializerCodegen.GenerateDeserializerBody(ctx, type, map[type].ReaderILGen);
            }

            #if GENERATE_SWITCH
            var ilGen = serializerSwitchMethod.GetILGenerator();
            SerializerCodegen.GenerateSerializerSwitch(ctx, ilGen, map);
            s_serializerSwitch = (SerializerSwitch)serializerSwitchMethod.CreateDelegate(typeof(SerializerSwitch));

            ilGen = deserializerSwitchMethod.GetILGenerator();
            DeserializerCodegen.GenerateDeserializerSwitch(ctx, ilGen, map);
            s_deserializerSwitch = (DeserializerSwitch)deserializerSwitchMethod.CreateDelegate(typeof(DeserializerSwitch));
            #else
            foreach (var kvp in map)
            {
                kvp.Value.serializer = GetSerializationInvoker(null, kvp.Value.WriterMethodInfo, kvp.Key, (int)kvp.Value.TypeID);
                kvp.Value.deserializer = GetDeserializationInvoker(null, kvp.Value.ReaderMethodInfo, kvp.Key, (int)kvp.Value.TypeID);
            }
            #endif

            return map;
        }
开发者ID:smalinin,项目名称:netserializer,代码行数:67,代码来源:Main.cs

示例11: GenerateDynamic

		static void GenerateDynamic(Dictionary<Type, TypeData> map)
		{
			/* generate stubs */
			foreach (var kvp in map)
			{
				var type = kvp.Key;
				var td = kvp.Value;

				if (!td.IsGenerated)
					continue;

				var writerDm = SerializerCodegen.GenerateDynamicSerializerStub(type);
				td.WriterMethodInfo = writerDm;
				td.WriterILGen = writerDm.GetILGenerator();

				var readerDm = DeserializerCodegen.GenerateDynamicDeserializerStub(type);
				td.ReaderMethodInfo = readerDm;
				td.ReaderILGen = readerDm.GetILGenerator();
			}

			var serializerSwitchMethod = new DynamicMethod("SerializerSwitch", null,
				new Type[] { typeof(Stream), typeof(object) },
				typeof(Serializer), true);
			serializerSwitchMethod.DefineParameter(1, ParameterAttributes.None, "stream");
			serializerSwitchMethod.DefineParameter(2, ParameterAttributes.None, "value");
			var serializerSwitchMethodInfo = serializerSwitchMethod;

			var deserializerSwitchMethod = new DynamicMethod("DeserializerSwitch", null,
				new Type[] { typeof(Stream), typeof(object).MakeByRefType() },
				typeof(Serializer), true);
			deserializerSwitchMethod.DefineParameter(1, ParameterAttributes.None, "stream");
			deserializerSwitchMethod.DefineParameter(2, ParameterAttributes.Out, "value");
			var deserializerSwitchMethodInfo = deserializerSwitchMethod;

			var ctx = new CodeGenContext(map, serializerSwitchMethodInfo, deserializerSwitchMethodInfo);

			/* generate bodies */

			foreach (var kvp in map)
			{
				var type = kvp.Key;
				var td = kvp.Value;

				if (!td.IsGenerated)
					continue;

				td.TypeSerializer.GenerateWriterMethod(type, ctx, td.WriterILGen);
				td.TypeSerializer.GenerateReaderMethod(type, ctx, td.ReaderILGen);
			}

			var ilGen = serializerSwitchMethod.GetILGenerator();
			SerializerCodegen.GenerateSerializerSwitch(ctx, ilGen, map);
			s_serializerSwitch = (SerializerSwitch)serializerSwitchMethod.CreateDelegate(typeof(SerializerSwitch));

			ilGen = deserializerSwitchMethod.GetILGenerator();
			DeserializerCodegen.GenerateDeserializerSwitch(ctx, ilGen, map);
			s_deserializerSwitch = (DeserializerSwitch)deserializerSwitchMethod.CreateDelegate(typeof(DeserializerSwitch));
		}
开发者ID:ppdai,项目名称:TripSerializer.Net,代码行数:58,代码来源:Main.cs

示例12: CreateSetAction

        private Action<object, object> CreateSetAction()
        {
            if (null == this.SetMethod)
            {
                throw new InvalidOperationException(
                    string.Format("Cannot find a writable \"{0}\" from the type \"{1}\".", this.PropertyName, this.TargetType.FullName));
            }
            DynamicMethod method = new DynamicMethod("SetValue", null, new Type[] { typeof(object), typeof(object) });
            ILGenerator ilGenerator = method.GetILGenerator();
            Type paramType = this.SetMethod.GetParameters()[0].ParameterType;
            ilGenerator.DeclareLocal(paramType);
            ilGenerator.Emit(OpCodes.Ldarg_0);
            ilGenerator.Emit(OpCodes.Castclass, this.TargetType);
            ilGenerator.Emit(OpCodes.Ldarg_1);
            if (paramType.IsValueType)
            {
                ilGenerator.Emit(OpCodes.Unbox, paramType);
                if (valueTpyeOpCodes.ContainsKey(paramType))
                {
                    OpCode load = (OpCode)valueTpyeOpCodes[paramType];
                    ilGenerator.Emit(load);
                }
                else
                {
                    ilGenerator.Emit(OpCodes.Ldobj, paramType);
                }
            }
            else
            {
                ilGenerator.Emit(OpCodes.Castclass, paramType); 
            }

            ilGenerator.EmitCall(OpCodes.Callvirt, this.SetMethod, null);
            ilGenerator.Emit(OpCodes.Ret);

            method.DefineParameter(1, ParameterAttributes.In, "obj");
            method.DefineParameter(2, ParameterAttributes.In, "value");
            return (Action<object, object>)method.CreateDelegate(typeof(Action<object, object>));
        }
开发者ID:sosokk,项目名称:YiFen.Library,代码行数:39,代码来源:PropertyAccessor.cs

示例13: CreateTestMethod

        /// <summary>
        /// Creates a dynamic method for testing units. All units take the same parameters.
        /// </summary>
        /// <param name="runner">The runner.</param>
        /// <returns></returns>
        public static DynamicUnitTiming CreateTestMethod(MethodRunner runner)
        {
            // Create the basic signature.
            var signature = new[] { typeof(object), typeof(int) };
            var method = new DynamicMethod("DynamicUnitTest" + (counter++),
                                           typeof(void),
                                           signature,
                                           typeof(MethodRunnerCompiler));

            // Create an IL generator for the method body.
            ILGenerator il = method.GetILGenerator(256);

            // We determine what type of IL code we generate based on the singleton type.
            if (runner.TimingAttribute.Singleton)
            {
                // Create a single call version.
                CreateSingleton(runner, il);
            }
            else
            {
                // Create the local variables.
                il.DeclareLocal(typeof(int));
                il.DeclareLocal(typeof(bool));

                // Declare the labels.
                Label loopLabel = il.DefineLabel();
                Label topLabel = il.DefineLabel();

                // Assign zero to the count variable.
                il.Emit(OpCodes.Ldc_I4_0);
                il.Emit(OpCodes.Stloc_0);
                il.Emit(OpCodes.Br_S, loopLabel);

                // Build up the actual execution.
                il.MarkLabel(topLabel);

                // Figure out how to call this method.
                il.Emit(OpCodes.Ldarg_0);

                switch (runner.MethodSignature)
                {
                case MethodSignature.CountInt32:
                    il.Emit(OpCodes.Ldloc_0);
                    break;
                case MethodSignature.CountIterationInt32:
                    il.Emit(OpCodes.Ldloc_0);
                    il.Emit(OpCodes.Ldarg_1);
                    break;
                }

                il.EmitCall(OpCodes.Call, runner.Method, null);

                // Increment the counter.
                il.Emit(OpCodes.Ldloc_0);
                il.Emit(OpCodes.Ldc_I4_1);
                il.Emit(OpCodes.Add);
                il.Emit(OpCodes.Stloc_0);

                // Create the loop test. This loads the count variable and compares
                // it to the second argument (iterations).
                il.MarkLabel(loopLabel);

                il.Emit(OpCodes.Ldloc_0);
                il.Emit(OpCodes.Ldarg_1);
                il.Emit(OpCodes.Clt);

                il.Emit(OpCodes.Stloc_1);
                il.Emit(OpCodes.Ldloc_1);
                il.Emit(OpCodes.Brtrue_S, topLabel);
            }

            // Finish up with a return IL.
            il.Emit(OpCodes.Ret);

            // Create the paramters.
            method.DefineParameter(0, ParameterAttributes.In, "target");
            method.DefineParameter(1, ParameterAttributes.In, "iteration");

            // Create the delegate and return it.
            return (DynamicUnitTiming) method.CreateDelegate(typeof(DynamicUnitTiming));
        }
开发者ID:dmoonfire,项目名称:unit-timing-cil,代码行数:86,代码来源:MethodRunnerCompiler.cs

示例14: BuildConfigureCapsMethod

        /// <summary>
        /// Create DynamicMethod that configures capabilities using System.Web.Configuration.BrowserCapabilitiesFactory (or similar) type.
        /// </summary>
        /// <param name="BrowserCapabilitiesFactoryType">Type with ConfigureBrowserCapabilities and ConfigureCustomCapabilities methods.</param>
        /// <remarks>
        /// Generated method performs following code:
        /// {
        ///     var capsFactory = new System.Web.Configuration.BrowserCapabilitiesFactory();
        ///     capsFactory.ConfigureBrowserCapabilities(headers, browserCaps);
        ///     capsFactory.ConfigureCustomCapabilities(headers, browserCaps);
        /// }
        /// </remarks>
        private static Action<NameValueCollection, HttpBrowserCapabilities> BuildConfigureCapsMethod(Type/*!*/BrowserCapabilitiesFactoryType)
        {
            Debug.Assert(BrowserCapabilitiesFactoryType != null);

            var method_ctor = BrowserCapabilitiesFactoryType.GetConstructor(Type.EmptyTypes);
            var method_ConfigureBrowserCapabilities = BrowserCapabilitiesFactoryType.GetMethod("ConfigureBrowserCapabilities");
            var method_ConfigureCustomCapabilities = BrowserCapabilitiesFactoryType.GetMethod("ConfigureCustomCapabilities");

            if (method_ctor == null) throw new InvalidOperationException(string.Format("{0} does not implement .ctor.", BrowserCapabilitiesFactoryType.ToString()));
            if (method_ConfigureBrowserCapabilities == null) throw new InvalidOperationException(string.Format("{0} does not implement {1}.", BrowserCapabilitiesFactoryType.ToString(), "ConfigureBrowserCapabilities"));
            if (method_ConfigureCustomCapabilities == null) throw new InvalidOperationException(string.Format("{0} does not implement {1}.", BrowserCapabilitiesFactoryType.ToString(), "ConfigureCustomCapabilities"));

            var method = new DynamicMethod("<dynamic>.BrowserCapabilitiesFactory", typeof(void), new Type[] { typeof(NameValueCollection), typeof(HttpBrowserCapabilities) });
            var il = new PHP.Core.Emit.ILEmitter(method);

            method.DefineParameter(1, System.Reflection.ParameterAttributes.None, "headers");
            method.DefineParameter(2, System.Reflection.ParameterAttributes.None, "browserCaps");

            // var capsFactory = new System.Web.Configuration.BrowserCapabilitiesFactory();
            var loc_factory = il.DeclareLocal(BrowserCapabilitiesFactoryType);
            il.Emit(OpCodes.Newobj, method_ctor);
            il.Stloc(loc_factory);

            // capsFactory.ConfigureBrowserCapabilities(headers, browserCaps);
            il.Ldloc(loc_factory);
            il.Ldarg(0);
            il.Ldarg(1);
            il.Emit(OpCodes.Callvirt, method_ConfigureBrowserCapabilities);

            // capsFactory.ConfigureCustomCapabilities(headers, browserCaps);
            il.Ldloc(loc_factory);
            il.Ldarg(0);
            il.Ldarg(1);
            il.Emit(OpCodes.Callvirt, method_ConfigureCustomCapabilities);

            // ret
            il.Emit(OpCodes.Ret);

            // done
            return (Action<NameValueCollection, HttpBrowserCapabilities>)method.CreateDelegate(typeof(Action<NameValueCollection, HttpBrowserCapabilities>));
        }
开发者ID:dw4dev,项目名称:Phalanger,代码行数:53,代码来源:Web.CLR.cs

示例15: CreateGetFunction

        /// <summary>
        /// Method CreateGetFunction.
        /// </summary>
        /// <param name="getMethod">MethodInfo of get method.</param>
        /// <returns>GetFunction delegate.</returns>
        private GetFunction<object, object> CreateGetFunction(MethodInfo getMethod)
        {
            DynamicMethod method = new DynamicMethod("GetValue", typeof(object), new Type[] { typeof(object) });

            ILGenerator ilGenerator = method.GetILGenerator();

            ilGenerator.DeclareLocal(typeof(object));
            ilGenerator.Emit(OpCodes.Ldarg_0);
            ilGenerator.Emit(OpCodes.Castclass, this.TargetType);
            ilGenerator.EmitCall(OpCodes.Call, getMethod, null);

            if (getMethod.ReturnType.IsValueType)
            {
                ilGenerator.Emit(OpCodes.Box, getMethod.ReturnType);
            }

            ilGenerator.Emit(OpCodes.Stloc_0);
            ilGenerator.Emit(OpCodes.Ldloc_0);
            ilGenerator.Emit(OpCodes.Ret);

            method.DefineParameter(1, ParameterAttributes.In, "value");

            return (GetFunction<object, object>)method.CreateDelegate(typeof(GetFunction<object, object>));
        }
开发者ID:kangwl,项目名称:KANG.Frame,代码行数:29,代码来源:PropertyAccessor.cs


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