Esempio n. 1
0
        // Handles field like events (i.e, no add/remove accessors)
        public override void VisitEventFieldDeclaration(EventFieldDeclarationSyntax node)
        {
            /*
             * .field private class [mscorlib]System.EventHandler TheEvent
             * .event [mscorlib]System.EventHandler TheEvent
             * {
             *          .addon instance void Test::add_TheEvent(class [mscorlib]System.EventHandler)
             *          .removeon instance void Test::remove_TheEvent(class [mscorlib]System.EventHandler)
             * }
             */

            //TODO: semantic model fails to resolve the event. Bug?
            //var eventSymbol = Context.SemanticModel.GetDeclaredSymbol(node);

            eventDeclaringTypeVar = Context.DefinitionVariables.GetLastOf(MemberKind.Type).VariableName;

            var backingFieldVar = string.Empty;

            var declaringType = node.ResolveDeclaringType();

            if (!declaringType.IsKind(SyntaxKind.InterfaceDeclaration))
            {
                backingFieldVar = AddBackingField(node); // backing field will have same name as the event
            }

            var eventType = ResolveType(node.Declaration.Type);

            var isStatic          = node.Modifiers.Any(m => m.IsKind(SyntaxKind.StaticKeyword));
            var addAccessorVar    = AddAddAccessor(node, backingFieldVar, isStatic, declaringType, eventType);
            var removeAccessorVar = AddRemoveAccessor(node, backingFieldVar, isStatic, declaringType, eventType);

            AddCecilExpression($"{eventDeclaringTypeVar}.Methods.Add({addAccessorVar});");
            AddCecilExpression($"{eventDeclaringTypeVar}.Methods.Add({removeAccessorVar});");

            var eventName = node.Declaration.Variables[0].Identifier.Text;

            var evtDefVar = AddEventDefinition(eventDeclaringTypeVar, eventName, eventType, addAccessorVar, removeAccessorVar);

            HandleAttributesInMemberDeclaration(node.AttributeLists, evtDefVar);
        }
Esempio n. 2
0
        private string AddBackingField(EventFieldDeclarationSyntax node)
        {
            var privateModifier       = SyntaxFactory.Token(SyntaxKind.PrivateKeyword); // always private no matter the accessibility of the event
            var accessibilityModifier = node.Modifiers.FirstOrDefault(m => m.IsKind(SyntaxKind.PublicKeyword) || m.IsKind(SyntaxKind.InternalKeyword));
            var backingFieldModifiers = accessibilityModifier == default
                ? node.Modifiers.Add(privateModifier)
                : node.Modifiers.Replace(accessibilityModifier, privateModifier);

            var fields = FieldDeclarationVisitor.HandleFieldDeclaration(Context, node, node.Declaration, backingFieldModifiers, node.ResolveDeclaringType());

            return(fields.First());
        }