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


C# SyntaxAnnotation.AddAnnotationToSymbol方法代码示例

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


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

示例1: EnsureEventHandler

        /// <summary>
        /// Ensure that an event handler exists for a given event.
        /// </summary>
        /// <param name="thisDocument">The document corresponding to this operation.</param>
        /// <param name="targetDocument">The document to generate the event handler in if it doesn't
        /// exist.</param>
        /// <param name="className">The name of the type to generate the event handler in.</param>
        /// <param name="objectName">The name of the event member (if <paramref
        /// name="useHandlesClause"/> is true)</param>
        /// <param name="objectTypeName">The name of the type containing the event.</param>
        /// <param name="nameOfEvent">The name of the event member in <paramref
        /// name="objectTypeName"/></param>
        /// <param name="eventHandlerName">The name of the method to be hooked up to the
        /// event.</param>
        /// <param name="itemidInsertionPoint">The VS itemid of the file to generate the event
        /// handler in.</param>
        /// <param name="useHandlesClause">If true, a vb "Handles" clause will be generated for the
        /// handler.</param>
        /// <param name="additionalFormattingRule">An additional formatting rule that can be used to
        /// format the newly inserted method</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        /// <returns>Either the unique id of the method if it already exists, or the unique id of
        /// the to be generated method, the text of the to be generated method, and the position in
        /// <paramref name="itemidInsertionPoint"/> where the text should be inserted.</returns>
        public static Tuple<string, string, VsTextSpan> EnsureEventHandler(
            Document thisDocument,
            Document targetDocument,
            string className,
            string objectName,
            string objectTypeName,
            string nameOfEvent,
            string eventHandlerName,
            uint itemidInsertionPoint,
            bool useHandlesClause,
            IFormattingRule additionalFormattingRule,
            CancellationToken cancellationToken)
        {
            var thisCompilation = thisDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
            var type = thisCompilation.GetTypeByMetadataName(className);

            var existingEventHandlers = GetCompatibleEventHandlers(targetDocument, className, objectTypeName, nameOfEvent, cancellationToken);
            var existingHandler = existingEventHandlers.SingleOrDefault(e => e.Item1 == eventHandlerName);
            if (existingHandler != null)
            {
                return Tuple.Create(existingHandler.Item2, (string)null, default(VsTextSpan));
            }

            // Okay, it doesn't exist yet.  Let's create it.
            var codeGenerationService = targetDocument.GetLanguageService<ICodeGenerationService>();
            var syntaxFactory = targetDocument.GetLanguageService<SyntaxGenerator>();
            var eventMember = GetEventSymbol(thisDocument, objectTypeName, nameOfEvent, type, cancellationToken);
            if (eventMember == null)
            {
                throw new InvalidOperationException();
            }

            var eventType = ((IEventSymbol)eventMember).Type;
            if (eventType.Kind != SymbolKind.NamedType || ((INamedTypeSymbol)eventType).DelegateInvokeMethod == null)
            {
                throw new InvalidOperationException(ServicesVSResources.EventTypeIsInvalid);
            }

            var handlesExpressions = useHandlesClause ?
                new[]
                {
                    syntaxFactory.MemberAccessExpression(
                        objectName != null ? syntaxFactory.IdentifierName(objectName) : syntaxFactory.ThisExpression(),
                        syntaxFactory.IdentifierName(nameOfEvent))
                }
            : null;

            var invokeMethod = ((INamedTypeSymbol)eventType).DelegateInvokeMethod;
            var newMethod = CodeGenerationSymbolFactory.CreateMethodSymbol(
                attributes: null,
                accessibility: Accessibility.Protected,
                modifiers: new DeclarationModifiers(),
                returnType: targetDocument.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken).GetSpecialType(SpecialType.System_Void),
                explicitInterfaceSymbol: null,
                name: eventHandlerName,
                typeParameters: null,
                parameters: invokeMethod.Parameters.ToArray(),
                statements: null,
                handlesExpressions: handlesExpressions);

            var annotation = new SyntaxAnnotation();
            newMethod = annotation.AddAnnotationToSymbol(newMethod);
            var codeModel = targetDocument.Project.LanguageServices.GetService<ICodeModelNavigationPointService>();
            var syntaxFacts = targetDocument.Project.LanguageServices.GetService<ISyntaxFactsService>();

            var targetSyntaxTree = targetDocument.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken);

            var position = type.Locations.First(loc => loc.SourceTree == targetSyntaxTree).SourceSpan.Start;
            var destinationType = syntaxFacts.GetContainingTypeDeclaration(targetSyntaxTree.GetRoot(cancellationToken), position);
            var insertionPoint = codeModel.GetEndPoint(destinationType, EnvDTE.vsCMPart.vsCMPartBody);

            if (insertionPoint == null)
            {
                throw new InvalidOperationException(ServicesVSResources.MemberInsertionFailed);
            }

//.........这里部分代码省略.........
开发者ID:ehsansajjad465,项目名称:roslyn,代码行数:101,代码来源:ContainedLanguageCodeSupport.cs

示例2: GenerateProperty

        protected IPropertySymbol GenerateProperty(string propertyName, string fieldName, Accessibility accessibility, IFieldSymbol field, INamedTypeSymbol containingSymbol, SyntaxAnnotation annotation, Document document, CancellationToken cancellationToken)
        {
            var factory = document.GetLanguageService<SyntaxGenerator>();

            var propertySymbol = annotation.AddAnnotationToSymbol(CodeGenerationSymbolFactory.CreatePropertySymbol(containingType: containingSymbol,
                attributes: SpecializedCollections.EmptyList<AttributeData>(),
                accessibility: ComputeAccessibility(accessibility, field.Type),
                modifiers: new DeclarationModifiers(isStatic: field.IsStatic, isReadOnly: field.IsReadOnly, isUnsafe: field.IsUnsafe()),
                type: field.Type,
                explicitInterfaceSymbol: null,
                name: propertyName,
                parameters: SpecializedCollections.EmptyList<IParameterSymbol>(),
                getMethod: CreateGet(fieldName, field, factory),
                setMethod: field.IsReadOnly || field.IsConst ? null : CreateSet(fieldName, field, factory)));

            return Simplifier.Annotation.AddAnnotationToSymbol(
                Formatter.Annotation.AddAnnotationToSymbol(propertySymbol));
        }
开发者ID:rgani,项目名称:roslyn,代码行数:18,代码来源:AbstractEncapsulateFieldService.cs

示例3: RewriteFieldNameAndAccessibility

        protected async override Task<SyntaxNode> RewriteFieldNameAndAccessibility(string originalFieldName, bool makePrivate, Document document, SyntaxAnnotation declarationAnnotation, CancellationToken cancellationToken)
        {
            var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            var declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(declarationAnnotation).FirstOrDefault();

            // There may be no field to rewrite if this document is part of a set of linked files
            // and the declaration is not conditionally compiled in this document's project.
            if (declarator == null)
            {
                return root;
            }

            var tempAnnotation = new SyntaxAnnotation();
            var escapedName = originalFieldName.EscapeIdentifier();
            var newIdentifier = SyntaxFactory.Identifier(
                    leading: SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker),
                    contextualKind: SyntaxKind.IdentifierName,
                    text: escapedName,
                    valueText: originalFieldName,
                    trailing: SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker))
                .WithTrailingTrivia(declarator.Identifier.TrailingTrivia)
                .WithLeadingTrivia(declarator.Identifier.LeadingTrivia);

            var updatedDeclarator = declarator.WithIdentifier(newIdentifier).WithAdditionalAnnotations(tempAnnotation);

            root = root.ReplaceNode(declarator, updatedDeclarator);
            document = document.WithSyntaxRoot(root);

            var declaration = root.GetAnnotatedNodes<SyntaxNode>(tempAnnotation).First().Parent as VariableDeclarationSyntax;

            if (declaration.Variables.Count == 1)
            {
                var fieldSyntax = declaration.Parent as FieldDeclarationSyntax;

                var modifierKinds = new[] { SyntaxKind.PrivateKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.InternalKeyword, SyntaxKind.PublicKeyword };

                if (makePrivate)
                {
                    var modifiers = SpecializedCollections.SingletonEnumerable(SyntaxFactory.Token(SyntaxKind.PrivateKeyword))
                                                            .Concat(fieldSyntax.Modifiers.Where(m => !modifierKinds.Contains(m.Kind())));

                    root = root.ReplaceNode(fieldSyntax, fieldSyntax.WithModifiers(
                        SyntaxFactory.TokenList(modifiers))
                            .WithAdditionalAnnotations(Formatter.Annotation)
                            .WithLeadingTrivia(fieldSyntax.GetLeadingTrivia())
                            .WithTrailingTrivia(fieldSyntax.GetTrailingTrivia()));
                }
            }
            else if (declaration.Variables.Count > 1 && makePrivate)
            {
                document = document.WithSyntaxRoot(root);
                var codeGenService = document.GetLanguageService<ICodeGenerationService>();
                var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

                root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

                declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(tempAnnotation).First();
                declaration = declarator.Parent as VariableDeclarationSyntax;

                var field = semanticModel.GetDeclaredSymbol(declarator, cancellationToken) as IFieldSymbol;

                var fieldToAdd = declarationAnnotation.AddAnnotationToSymbol(CodeGenerationSymbolFactory.CreateFieldSymbol(
                    field.GetAttributes(),
                    Accessibility.Private,
                    new DeclarationModifiers(isStatic: field.IsStatic, isReadOnly: field.IsReadOnly, isConst: field.IsConst),
                    field.Type,
                    field.Name,
                    field.HasConstantValue,
                    field.ConstantValue,
                    declarator.Initializer));

                var withField = await codeGenService.AddFieldAsync(document.Project.Solution, field.ContainingType, fieldToAdd, new CodeGenerationOptions(), cancellationToken).ConfigureAwait(false);
                root = await withField.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

                declarator = root.GetAnnotatedNodes<VariableDeclaratorSyntax>(tempAnnotation).First();
                declaration = declarator.Parent as VariableDeclarationSyntax;

                return root.RemoveNode(declarator, SyntaxRemoveOptions.KeepNoTrivia);
            }

            return root;
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:83,代码来源:CSharpEncapsulateFieldService.cs


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