コード例 #1
0
        /// <summary>
        /// Add switch registering to a class.
        /// </summary>
        /// <param name="clazz">The class to register switch.</param>
        /// <param name="context">The weaving context.</param>
        /// <param name="switchData">Data of switches.</param>
        /// <param name="statistics">Weaving statistics.</param>
        public static void Weave(TypeDefinition clazz, IWeavingContext context, IReadOnlyList <SwitchInitializingData> switchData, IClassWeavingStatisticsBuilder statistics)
        {
#if DEBUG
            if (clazz == null)
            {
                throw new ArgumentNullException("clazz");
            }

            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            if (switchData == null || !switchData.Any())
            {
                throw new ArgumentNullException("switchData");
            }

            if (statistics == null)
            {
                throw new ArgumentNullException("statistics");
            }
#endif
            var staticConstructor      = clazz.Methods.FirstOrDefault(mthd => mthd.IsStaticConstructor());
            MethodDefinition method    = null;
            ILProcessor      processor = null;
            if (staticConstructor == null)
            {
                method = new MethodDefinition(
                    ".cctor",
                    MethodAttributes.Static | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName,
                    context.GetTypeReference(typeof(void)));
                processor = method.Body.GetILProcessor();
                method.Body.Instructions.Add(processor.Create(OpCodes.Ret));
                clazz.Methods.Add(method);
            }
            else
            {
                method    = staticConstructor;
                processor = method.Body.GetILProcessor();
            }

            var typeName     = clazz.GetFullName();
            var instructions = new List <Instruction>();
            foreach (var data in switchData)
            {
                RegisterSwitch(instructions, processor, context, data, typeName);
                statistics.AddSwitchWeavingRecord(StatisticsFactory.InitializeSwitchWeavingRecord(typeName, data.Property, data.MethodSignature, data.Aspect, data.Field.Name, data.Value));
            }

            CompleteSwitchRegistration(method, instructions, processor, context, typeName);
        }