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


C# InstructionBlock.DefineLocalVariable方法代码示例

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


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

示例1: Weave

        /// <summary>
        /// Weaves the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        /// <param name="block">The block.</param>
        public void Weave(WeavingContext context, InstructionBlock block)
        {
            LocalVariableSymbol parameters = block.DefineLocalVariable(context.Method.Module.FindType(typeof(ParameterDictionary), BindingOptions.Default), NameGenerator.Generate("parameters"));

            InstructionSequence entrySequence = context.Method.MethodBody.CreateInstructionSequence();
            block.AddInstructionSequence(entrySequence, NodePosition.Before, null);

            InstructionWriter writer = context.InstructionWriter;
            writer.AttachInstructionSequence(entrySequence);
            writer.EmitSymbolSequencePoint(SymbolSequencePoint.Hidden);

            writer.EmitInstructionMethod(OpCodeNumber.Call, context.Method.Module.FindMethod(typeof(InternalHelperMethods).GetMethod("CreateParameterCollection"), BindingOptions.Default));

            IMethod add = context.Method.Module.FindMethod(typeof(ParameterDictionary).GetMethod("Add", new[] { typeof(string), typeof(object) }), BindingOptions.Default);

            short parameterIndex = context.Method.IsStatic ? (short)0 : (short)1;
            foreach (var parameter in method.Parameters)
            {
                writer.EmitInstruction(OpCodeNumber.Dup);

                writer.EmitInstructionString(OpCodeNumber.Ldstr, new LiteralString(parameter.Name));
                writer.EmitInstructionInt16(OpCodeNumber.Ldarg, parameterIndex++);

                if (parameter.ParameterType.GetSystemType(null, null).IsValueType)
                {
                    writer.EmitInstructionType(OpCodeNumber.Box, parameter.ParameterType);
                }

                writer.EmitInstructionMethod(OpCodeNumber.Callvirt, add);
            }

            writer.EmitInstructionLocalVariable(OpCodeNumber.Stloc, parameters);

            writer.DetachInstructionSequence();
        }
开发者ID:zevinganez,项目名称:code-o-matic,代码行数:40,代码来源:BuildParameterCollectionAdvice.cs

示例2: AddPropertyGuard

        public static void AddPropertyGuard(PropertyDeclaration property, MethodBodyTransformationContext context, InstructionBlock block, InstructionWriter writer)
        {
            var propertyType = property.PropertyType;
            var methodBody = block.MethodBody;

            var sequence = block.AddInstructionSequence(null, NodePosition.After, null);
            if (sequence == null) return;

            var oldValueVariable =
                block.DefineLocalVariable(propertyType, string.Format("old{0}Value", property.Name));
            var assets = GetTransformationAssets(property.Module);

            writer.AttachInstructionSequence(sequence);
            var isLocationBinding = CheckIfIsLocationBinding(methodBody,assets);
            if (isLocationBinding) {
                writer.AssignValue_LocalVariable(oldValueVariable
                    , () => writer.Call_MethodOnTarget(property.GetGetter()
                        ,
                        () => {
                            //Load the instance parameter of the SetValue method
                            //and convert it to the type
                            writer.EmitInstruction(OpCodeNumber.Ldarg_1);
                            //writer.EmitInstructionLoadIndirect(Assets.ObjectTypeSignature);
                            writer.EmitInstructionType(OpCodeNumber.Ldobj, assets.ObjectTypeSignature);
                            writer.EmitConvertFromObject(property.Parent);
                        }
                    )
                );
                //On the location binding the value parameter is at psotion 3
                writer.EmitInstruction(OpCodeNumber.Ldarg_3);
            } else {
                writer.AssignValue_LocalVariable(oldValueVariable,
                                                    () => writer.Get_PropertyValue(property));
                //For a normal property the value parameter is at position 1
                writer.EmitInstruction(OpCodeNumber.Ldarg_1);
            }
            if (propertyType.IsStruct()) {
                writer.EmitInstructionType(OpCodeNumber.Box, propertyType);
            }
            writer.Box_LocalVariableIfNeeded(oldValueVariable);
            var isPrimitive = propertyType.IsPrimitive();
            if (isPrimitive) {
                writer.Compare_Primitives();
            } else {
                //TODO: Try and use the equality operator when present
                writer.Compare_Objects(assets.ObjectEqualsMethod);
            }
            //writer.Leave_IfTrue(_context.LeaveBranchTarget);
            writer.Leave_IfTrue(context.LeaveBranchTarget);
            writer.DetachInstructionSequence();
        }
开发者ID:DamianReeves,项目名称:PostEdge,代码行数:51,代码来源:EnhancePropertySetterMethodBodyWrappingImplementation.cs

示例3: WeaveException

        private void WeaveException(WeavingContext context, InstructionBlock block)
        {
            LogLevel level = this.attribute.ExceptionLevel;
              string text = this.attribute.ExceptionText;

              // Inject the logging code only if the logging is turned on.
              if (this.attribute.ExceptionLevel != LogLevel.None)
              {
            // Method being woven and the type the method is declared in.
            MethodDefDeclaration wovenMethod = context.Method;
            TypeDefDeclaration wovenType = wovenMethod.DeclaringType;

            // Objects that contain required methods, fields, etc.
            LogLevelSupportItem supportItem = this.parent.GetSupportItem(level);
            PerTypeLoggingData perTypeLoggingData = this.parent.GetPerTypeLoggingData(wovenType);

            // Get the tokens for the message template.
            StringBuilder messageFormatString = new StringBuilder();
            List<IMessageToken> nonStaticTokens = new List<IMessageToken>();
            List<IMessageToken> messageParts = TemplateParser.Tokenize(text, wovenMethod, attribute.IncludeParamName);
            MakeFormatString(messageParts, messageFormatString, nonStaticTokens);

            // As log4net does not provide an overload for the LogXXX() methods which would accept
            // both exception and array of arguments for a format string, disallow usage of dynamic
            // tokens in the template.
            if (nonStaticTokens.Count > 0)
            {
              throw new FormatException("Message for logging exception can contain only placeholders whose value can be expanded at weaving time.");
            }

            // Variable that stores the reference to the thrown exception.
            LocalVariableSymbol exception = block.DefineLocalVariable(context.Method.Module.FindType(typeof(Exception), BindingOptions.Default), "~ex~{0}");

            // Sequence that contains code that checks if the logging is enabled and logs the message.
            InstructionSequence logExceptionSequence = context.Method.MethodBody.CreateInstructionSequence();
            block.AddInstructionSequence(logExceptionSequence, NodePosition.Before, null);
            // Sequence that contains code that is executed after logging.
            InstructionSequence afterLoggingSequence = context.Method.MethodBody.CreateInstructionSequence();
            block.AddInstructionSequence(afterLoggingSequence, NodePosition.After, logExceptionSequence);

            // Emit code that checks if the logging is enabled and logs the message.
            context.InstructionWriter.AttachInstructionSequence(logExceptionSequence);
            context.InstructionWriter.EmitSymbolSequencePoint(SymbolSequencePoint.Hidden);
            context.InstructionWriter.EmitInstructionLocalVariable(OpCodeNumber.Stloc_S, exception);
            EmitLoggingEnabledCheck(context.InstructionWriter, supportItem, perTypeLoggingData, afterLoggingSequence);
            EmitLogStringException(context.InstructionWriter, perTypeLoggingData.Log, supportItem.LogStringExceptionMethod, messageFormatString.ToString(), exception);
            context.InstructionWriter.DetachInstructionSequence();

            // After logging is finished (or skipped), rethrow the exception.
            context.InstructionWriter.AttachInstructionSequence(afterLoggingSequence);
            context.InstructionWriter.EmitSymbolSequencePoint(SymbolSequencePoint.Hidden);
            context.InstructionWriter.EmitInstruction(OpCodeNumber.Rethrow);
            context.InstructionWriter.DetachInstructionSequence();
              }
              else
              {
            // Logging is turned off, just rethrow the exception.
            InstructionSequence rethrowSequence = context.Method.MethodBody.CreateInstructionSequence();
            block.AddInstructionSequence(rethrowSequence, NodePosition.Before, null);
            context.InstructionWriter.AttachInstructionSequence(rethrowSequence);
            context.InstructionWriter.EmitSymbolSequencePoint(SymbolSequencePoint.Hidden);
            context.InstructionWriter.EmitInstruction(OpCodeNumber.Rethrow);
            context.InstructionWriter.DetachInstructionSequence();
              }
        }
开发者ID:kamillangowski,项目名称:postsharp-user-plugins,代码行数:65,代码来源:LogAdvice.cs

示例4: EmitCreateFormatArgumentArray

        /// <summary>
        /// Emits the MSIL that creates local variable and initializes it with array of objects representing the specified tokens.
        /// </summary>
        /// <param name="context">Context for the weaving.</param>
        /// <param name="block">Block where the code has to be injected.</param>
        /// <param name="nonStaticTokens">List of tokens that the object array is created for.</param>
        /// <returns>Local variable that stores the reference to the array.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="context"/>, <paramref name="block"/> or <paramref name="nonStaticTokens"/> is <see langword="null"/>.</exception>
        /// <remarks>
        /// <para>Code emitted by this method makes no assumptions on the state of the evaluation stack 
        /// and it leaves the stack unmodified.</para>
        /// </remarks>
        private LocalVariableSymbol EmitCreateFormatArgumentArray(WeavingContext context, InstructionBlock block, IList<IMessageToken> nonStaticTokens)
        {
            if (context == null)
              {
            throw new ArgumentNullException("context");
              }
              if (block == null)
              {
            throw new ArgumentNullException("block");
              }
              if (nonStaticTokens == null)
              {
            throw new ArgumentNullException("nonStaticTokens");
              }

              InstructionWriter emitter = context.InstructionWriter;

              // Array that store arguments for the formatting.
              LocalVariableSymbol args = block.DefineLocalVariable(context.Method.Module.FindType(typeof(object[]), BindingOptions.Default), "~args~{0}");

              // Create the array for storing agruments for formatting (contains only dyncamic tokens).
              emitter.EmitInstructionInt32(OpCodeNumber.Ldc_I4, nonStaticTokens.Count);
              emitter.EmitInstructionType(OpCodeNumber.Newarr, this.parent.ObjectType);
              // Save the array into the local variable because it will be used multiple times.
              emitter.EmitInstructionLocalVariable(OpCodeNumber.Stloc, args);

              // Fill the array with the data.
              for (int index = 0; index < nonStaticTokens.Count; index++)
              {
            // Array to store the data in.
            emitter.EmitInstructionLocalVariable(OpCodeNumber.Ldloc, args);
            // Position in the array to store the data at.
            emitter.EmitInstructionInt32(OpCodeNumber.Ldc_I4, index);
            // Let the token generate the IL that pushes the argument onto the stack.
            nonStaticTokens[index].Emit(context);
            // Finally: store the generated object into the array at the given position.
            emitter.EmitInstruction(OpCodeNumber.Stelem_Ref);
              }

              return args;
        }
开发者ID:kamillangowski,项目名称:postsharp-user-plugins,代码行数:53,代码来源:LogAdvice.cs


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