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


C# MethodDefinition.GetCustomAttribute方法代码示例

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


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

示例1: AutoModifyMethod

        private void AutoModifyMethod(TypeDefinition targetType, MethodDefinition yourMethod,
			MemberActionAttribute memberAction)
        {
            Log_modifying_member("method", yourMethod);
            var bodySource = yourMethod;
            var insertAttribute = yourMethod.GetCustomAttribute<DuplicatesBodyAttribute>();
            if (insertAttribute != null) {
                //Note that the source type is resolved using yourMethod's module, which uses a different IMetadataResolver,
                //and thus will resolve the method from the target, unmodified assembly.

                var importSourceType = insertAttribute.SourceType != null
                    ? yourMethod.Module.Import((TypeReference) insertAttribute.SourceType)
                    : yourMethod.Module.Import(targetType);

                var importMethod = importSourceType.Resolve().GetMethods(insertAttribute.MethodName,
                    yourMethod.Parameters.Select(x => x.ParameterType)).SingleOrDefault();

                var others =
                    importSourceType.Resolve().Methods.Where(x => x.Name == insertAttribute.MethodName).ToArray();

                if (importMethod == null) {
                    throw Errors.Missing_member("method", yourMethod, insertAttribute.MethodName);
                }

                bodySource = importMethod;
            }
            var modifiesMemberAttr = memberAction as ModifiesMemberAttribute;
            var newMemberAttr = memberAction as NewMemberAttribute;
            ModificationScope scope;
            string targetMethodName;

            if (modifiesMemberAttr != null) {
                targetMethodName = modifiesMemberAttr.MemberName ?? yourMethod.Name;
                scope = modifiesMemberAttr.Scope;

            } else if (newMemberAttr != null) {
                targetMethodName = yourMethod.Name;
                scope = ModificationScope.All;
            } else {
                throw Errors.Unknown_action_attribute(memberAction);
            }
            var targetMethod =
                targetType.GetMethods(targetMethodName, yourMethod.Parameters.Select(x => x.ParameterType)).FirstOrDefault();

            if (targetMethod == null) {
                throw Errors.Missing_member("method", yourMethod, targetMethodName);
            }
            if (modifiesMemberAttr != null && targetMethod.IsAbstract && (scope & ModificationScope.Body) != 0) {
                throw Errors.Invalid_member("method", yourMethod, targetMethod.FullName,
                    "You cannot modify the body of an abstract method.");
            }

            ModifyMethod(targetMethod, yourMethod, scope & ~ModificationScope.Body, newMemberAttr != null);
            ModifyMethod(targetMethod, bodySource, ModificationScope.Body & scope, false);
        }
开发者ID:gitter-badger,项目名称:Patchwork,代码行数:55,代码来源:ModifyExisting.cs

示例2: TransferMethodBody

        /// <summary>
        /// Transfers the method body of yourMethod into the targetMethod, keeping everything neat and tidy, creating new copies of yourMethod's instructions.
        /// </summary>
        /// <param name="targetMethod">The target method.</param>
        /// <param name="yourMethod">Your instructions.</param>
        private void TransferMethodBody(MethodDefinition targetMethod, MethodDefinition yourMethod)
        {
            //TODO: This method needs to be refactored somehow. In particular, the IL transformation in PatchworkDebugRegisterAttribute needs to be applied separately.

            targetMethod.Body.Instructions.Clear();
            var injectManual = yourMethod.GetCustomAttribute<PatchworkDebugRegisterAttribute>();
            FieldReference debugFieldRef = null;

            _concat = _concat ?? targetMethod.Module.GetMethodLike(() => String.Concat("", ""));
            var instructionEquiv = new Dictionary<Instruction, Instruction>();
            targetMethod.Body.InitLocals = yourMethod.Body.Variables.Count > 0;

            targetMethod.Body.Variables.Clear();

            foreach (var yourVar in yourMethod.Body.Variables) {

                var targetVarType = FixTypeReference(yourVar.VariableType);
                var targetVar = new VariableDefinition(yourVar.Name, targetVarType);
                targetMethod.Body.Variables.Add(targetVar);
            }
            var ilProcesser = targetMethod.Body.GetILProcessor();
            if (injectManual != null) {
                var debugDeclType = (TypeReference) injectManual.DeclaringType ?? targetMethod.DeclaringType;
                var debugMember = injectManual.DebugFieldName;
                debugFieldRef = debugDeclType.Resolve().GetField(debugMember);
                if (debugFieldRef == null) {
                    throw Errors.Missing_member_in_attribute("field", yourMethod, debugMember);
                }
                ilProcesser.Emit(OpCodes.Ldstr, "");
                ilProcesser.Emit(OpCodes.Stsfld, debugFieldRef);
            }
            //branch instructions reference other instructions in the method body as branch targets.
            //in order to fix them, I will first have to reconstruct the other instructions in the body
            for (int i = 0; i < yourMethod.Body.Instructions.Count; i++) {
                var yourInstruction = yourMethod.Body.Instructions[i];
                var yourOperand = yourInstruction.Operand;
                //Note that properties or events are pure non-functional metadata, kind of like attributes.
                //They will never be directly referenced in a CIL instruction, though reflection is a different story of course.
                object targetOperand;
                OpCode targetOpcode = yourInstruction.OpCode;
                if (yourOperand is MethodReference) {
                    var yourMethodOperand = (MethodReference) yourOperand;
                    var memberAliasAttr = yourMethodOperand.Resolve().GetCustomAttribute<MemberAliasAttribute>();
                    if (memberAliasAttr != null && targetOpcode.EqualsAny(OpCodes.Call, OpCodes.Callvirt)) {
                        switch (memberAliasAttr.CallMode) {
                            case AliasCallMode.NonVirtual:
                                targetOpcode = OpCodes.Call;
                                break;
                            case AliasCallMode.Virtual:
                                targetOpcode = OpCodes.Callvirt;
                                break;
                        }
                    }
                    //FixMethodReference also resolves the aliased method, so processing MemberAliasAttribute isn't done yet.
                    var targetMethodRef = FixMethodReference(yourMethodOperand);
                    targetOperand = targetMethodRef;
                } else if (yourOperand is TypeReference) {
                    //includes references to type parameters
                    var yourTypeRef = (TypeReference) yourOperand;
                    targetOperand = FixTypeReference(yourTypeRef);
                } else if (yourOperand is FieldReference) {
                    var yourFieldRef = (FieldReference) yourOperand;
                    targetOperand = FixFieldReference(yourFieldRef);
                } else if (yourOperand is ParameterReference) {
                    var yourParamRef = (ParameterReference) yourOperand;
                    targetOperand = FixParamReference(targetMethod, yourParamRef);
                } else {
                    targetOperand = yourOperand;
                }

                var targetInstruction = Hacks.CreateInstruction(yourInstruction.OpCode, targetOperand);
                targetInstruction.OpCode = targetOpcode;
                targetInstruction.Operand = targetOperand;
                targetInstruction.SequencePoint = yourInstruction.SequencePoint;

                if (injectManual != null) {
                    targetInstruction.OpCode = SimplifyOpCode(targetInstruction.OpCode);
                }
                var lastInstr = ilProcesser.Body.Instructions.LastOrDefault();
                if (yourInstruction.SequencePoint != null && injectManual != null
                    && (lastInstr == null || !IsBreakingOpCode(lastInstr.OpCode))) {
                    var str = i == 0 ? "" : " ⇒ ";
                    str += yourInstruction.SequencePoint.StartLine;
                    ilProcesser.Emit(OpCodes.Ldsfld, debugFieldRef);
                    ilProcesser.Emit(OpCodes.Ldstr, str);
                    ilProcesser.Emit(OpCodes.Call, _concat);
                    ilProcesser.Emit(OpCodes.Stsfld, debugFieldRef);
                }
                instructionEquiv[yourInstruction] = targetInstruction;
                ilProcesser.Append(targetInstruction);
            }
            targetMethod.Body.ExceptionHandlers.Clear();
            if (yourMethod.Body.HasExceptionHandlers) {
                var handlers =
                    from exhandler in yourMethod.Body.ExceptionHandlers
//.........这里部分代码省略.........
开发者ID:GregRos,项目名称:Patchwork,代码行数:101,代码来源:ModifyExisting.cs

示例3: ModifyMethod

        private void ModifyMethod(TypeDefinition targetType, MethodDefinition yourMethod,
			MemberActionAttribute memberAction, MethodDefinition targetMethod)
        {
            Log_modifying_member("method", yourMethod);
            var insertAttribute = yourMethod.GetCustomAttribute<DuplicatesBodyAttribute>();
            var bodySource = insertAttribute == null ? yourMethod : GetBodySource(targetType, yourMethod, insertAttribute);
            ModificationScope scope = memberAction.Scope;
            if (scope.HasFlag(AdvancedModificationScope.ExplicitOverrides)) {
                targetMethod.Overrides.Clear();
                foreach (var explicitOverride in yourMethod.Overrides) {
                    targetMethod.Overrides.Add(FixMethodReference(explicitOverride));
                }
            }

            var attrFilter = AttrFilter(scope);
            CopyCustomAttributes(targetMethod, yourMethod, attrFilter);
            CopyCustomAttributes(targetMethod.MethodReturnType, yourMethod.MethodReturnType, attrFilter);
            for (int i = 0; i < yourMethod.Parameters.Count; i++) {
                CopyCustomAttributes(targetMethod.Parameters[i], yourMethod.Parameters[i], attrFilter);
            }
            for (int i = 0; i < yourMethod.GenericParameters.Count; i++) {
                CopyCustomAttributes(targetMethod.GenericParameters[i], yourMethod.GenericParameters[i], attrFilter);
            }

            if ((scope & ModificationScope.Accessibility) != 0) {
                targetMethod.SetAccessibility(yourMethod.GetAccessbility());
            }

            if (scope.HasFlag(ModificationScope.Body)) {
                if (yourMethod.Body != null) {
                    TransferMethodBody(targetMethod, bodySource);
                } else {
                    //this happens in abstract methods and some others.
                    targetMethod.Body = null;
                }
            }
            if (EmbedHistory) {
                targetMethod.AddPatchedByMemberAttribute(yourMethod);
            }

            var toggleAttributesAttr = yourMethod.GetCustomAttribute<ToggleMethodAttributes>();
            var toggleValue = toggleAttributesAttr?.Attributes ?? 0;
            targetMethod.Attributes ^= (MethodAttributes) toggleValue;
        }
开发者ID:GregRos,项目名称:Patchwork,代码行数:44,代码来源:ModifyExisting.cs

示例4: TransferMethodBody

        /// <summary>
        /// Fixes the cil instruction. Currently mutates yourInstruction rather than returning a new instruction, because creating a new instruction creates a bugg that I don't understand.
        /// </summary>
        /// <param name="targetMethod">The target method.</param>
        /// <param name="yourMethod">Your instructions.</param>
        /// <returns>The return type is a sequence because instructions can sometimes be fixed to multiple instructions.</returns>
        private void TransferMethodBody(MethodDefinition targetMethod, MethodDefinition yourMethod)
        {
            targetMethod.Body.Instructions.Clear();
            var injectManual = yourMethod.GetCustomAttribute<PatchworkDebugRegisterAttribute>();
            FieldReference debugFieldRef = null;

            var concat = targetMethod.Module.GetMethod(() => String.Concat("", ""));
            var instructionEquiv = new Dictionary<Instruction, Instruction>();
            targetMethod.Body.InitLocals = yourMethod.Body.Variables.Count > 0;

            targetMethod.Body.Variables.Clear();

            foreach (var yourVar in yourMethod.Body.Variables) {

                var targetVarType = FixTypeReference(yourVar.VariableType);
                var targetVar = new VariableDefinition(yourVar.Name, targetVarType);
                targetMethod.Body.Variables.Add(targetVar);
            }
            var ilProcesser = targetMethod.Body.GetILProcessor();
            if (injectManual != null) {
                var debugDeclType = (TypeReference)injectManual.DeclaringType ?? targetMethod.DeclaringType;
                var debugMember = injectManual.DebugFieldName;
                debugFieldRef = debugDeclType.Resolve().GetField(debugMember);
                ilProcesser.Emit(OpCodes.Ldstr, "");
                ilProcesser.Emit(OpCodes.Stsfld, debugFieldRef);
            }
            //branch instructions reference other instructions in the method body as branch targets.
            //in order to fix them, I will first have to reconstruct the other instructions in the body
            //and then find the correct instruction by index. Any changes to the IL will require a different way of
            for (int i = 0; i < yourMethod.Body.Instructions.Count; i++) {
                var yourInstruction = yourMethod.Body.Instructions[i];
                var yourOperand = yourInstruction.Operand;
                //Note that properties or events are pure non-functional metadata, kind of like attributes.
                //They will never be directly referenced in a CIL instruction, though reflection is a different story of course.
                object targetOperand;

                if (yourOperand is MethodReference) {
                    var yourMethodOperand = (MethodReference) yourOperand;
                    var targetMethodRef = FixMethodReference(yourMethodOperand);
                    targetOperand = targetMethodRef;
                } else if (yourOperand is TypeReference) {
                    //includes references to type parameters
                    var yourTypeRef = (TypeReference) yourOperand;
                    targetOperand = FixTypeReference(yourTypeRef);
                } else if (yourOperand is FieldReference) {
                    var yourFieldRef = (FieldReference) yourOperand;
                    targetOperand = FixFieldReference(yourFieldRef);
                } else if (yourOperand is ParameterReference) {
                    var yourParamRef = (ParameterReference) yourOperand;
                    targetOperand = FixParamReference(targetMethod, yourParamRef);
                } else {
                    targetOperand = yourOperand;
                }

                var targetInstruction = CecilHelper.CreateInstruction(yourInstruction.OpCode, targetOperand);
                targetInstruction.OpCode = yourInstruction.OpCode;
                targetInstruction.Operand = targetOperand;
                targetInstruction.SequencePoint = yourInstruction.SequencePoint;

                if (injectManual != null) {
                    targetInstruction.OpCode = SimplifyOpCode(targetInstruction.OpCode);
                }

                var lastInstr = ilProcesser.Body.Instructions.LastOrDefault();
                if (yourInstruction.SequencePoint != null && injectManual != null && (lastInstr == null ||!lastInstr.OpCode.EqualsAny(OpCodes.Leave, OpCodes.Leave_S, OpCodes.Ret, OpCodes.Rethrow, OpCodes.Throw))) {

                    var str = i == 0 ? "" : " ⇒ ";
                    str += yourInstruction.SequencePoint.StartLine;
                    ilProcesser.Emit(OpCodes.Ldsfld, debugFieldRef);
                    ilProcesser.Emit(OpCodes.Ldstr, str);
                    ilProcesser.Emit(OpCodes.Call, concat);
                    ilProcesser.Emit(OpCodes.Stsfld, debugFieldRef);
                }
                instructionEquiv[yourInstruction] = targetInstruction;
                ilProcesser.Append(targetInstruction);
            }
            targetMethod.Body.ExceptionHandlers.Clear();
            if (yourMethod.Body.HasExceptionHandlers) {
                var handlers =
                    from exhandler in yourMethod.Body.ExceptionHandlers
                    select new ExceptionHandler(exhandler.HandlerType) {
                        CatchType = exhandler.CatchType == null ? null : FixTypeReference(exhandler.CatchType),
                        HandlerStart = instructionEquiv[exhandler.HandlerStart],
                        HandlerEnd = instructionEquiv[exhandler.HandlerEnd],
                        TryStart = instructionEquiv[exhandler.TryStart],
                        TryEnd = instructionEquiv[exhandler.TryEnd],
                        FilterStart = exhandler.FilterStart == null ? null : instructionEquiv[exhandler.FilterStart]
                    };
                foreach (var exhandlr in handlers) {
                    targetMethod.Body.ExceptionHandlers.Add(exhandlr);
                }
            }

            foreach (var targetInstruction in ilProcesser.Body.Instructions) {
//.........这里部分代码省略.........
开发者ID:gitter-badger,项目名称:Patchwork,代码行数:101,代码来源:FixReferences.cs


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