• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# Syntax.TypeDeclarationSyntax类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中Microsoft.CodeAnalysis.CSharp.Syntax.TypeDeclarationSyntax的典型用法代码示例。如果您正苦于以下问题:C# TypeDeclarationSyntax类的具体用法?C# TypeDeclarationSyntax怎么用?C# TypeDeclarationSyntax使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



TypeDeclarationSyntax类属于Microsoft.CodeAnalysis.CSharp.Syntax命名空间,在下文中一共展示了TypeDeclarationSyntax类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: AnalyzeType

        private static void AnalyzeType(SyntaxNodeAnalysisContext context, TypeDeclarationSyntax typeDeclaration)
        {
            var previousFieldReadonly = true;
            var previousAccessLevel = AccessLevel.NotSpecified;
            var previousMemberStatic = true;
            foreach (var member in typeDeclaration.Members)
            {
                var field = member as FieldDeclarationSyntax;
                if (field == null)
                {
                    continue;
                }

                var currentFieldReadonly = field.Modifiers.Any(SyntaxKind.ReadOnlyKeyword);
                var currentAccessLevel = AccessLevelHelper.GetAccessLevel(field.Modifiers);
                currentAccessLevel = currentAccessLevel == AccessLevel.NotSpecified ? AccessLevel.Private : currentAccessLevel;
                var currentMemberStatic = field.Modifiers.Any(SyntaxKind.StaticKeyword);
                if (currentAccessLevel == previousAccessLevel
                    && currentMemberStatic
                    && previousMemberStatic
                    && currentFieldReadonly
                    && !previousFieldReadonly)
                {
                    context.ReportDiagnostic(Diagnostic.Create(Descriptor, NamedTypeHelpers.GetNameOrIdentifierLocation(field), AccessLevelHelper.GetName(currentAccessLevel)));
                }

                previousFieldReadonly = currentFieldReadonly;
                previousAccessLevel = currentAccessLevel;
                previousMemberStatic = currentMemberStatic;
            }
        }
开发者ID:robinsedlaczek,项目名称:StyleCopAnalyzers,代码行数:31,代码来源:SA1214StaticReadonlyElementsMustAppearBeforeStaticNonReadonlyElements.cs


示例2: OrdonnerMembres

        /// <summary>
        /// Réordonne les membres d'un type.
        /// </summary>
        /// <param name="document">Le document.</param>
        /// <param name="type">Le type.</param>
        /// <param name="jetonAnnulation">Le jeton d'annulation.</param>
        /// <returns>Le nouveau document.</returns>
        private async Task<Document> OrdonnerMembres(Document document, TypeDeclarationSyntax type, CancellationToken jetonAnnulation)
        {
            // On récupère la racine.
            var racine = await document
                .GetSyntaxRootAsync(jetonAnnulation)
                .ConfigureAwait(false);
            var modèleSémantique = await document.GetSemanticModelAsync(jetonAnnulation);

            // Pour une raison étrange, TypeDeclarationSyntax n'expose pas WithMembers() alors que les trois classes qui en héritent l'expose.
            // Il faut donc gérer les trois cas différemment...
            SyntaxNode nouveauType;
            if (type is ClassDeclarationSyntax)
            {
                nouveauType = (type as ClassDeclarationSyntax)
                    .WithMembers(SyntaxFactory.List(Partagé.OrdonnerMembres(type.Members, modèleSémantique)));
            }
            else if (type is InterfaceDeclarationSyntax)
            {
                nouveauType = (type as InterfaceDeclarationSyntax)
                    .WithMembers(SyntaxFactory.List(Partagé.OrdonnerMembres(type.Members, modèleSémantique)));
            }
            else
            {
                nouveauType = (type as StructDeclarationSyntax)
                    .WithMembers(SyntaxFactory.List(Partagé.OrdonnerMembres(type.Members, modèleSémantique)));
            }

            // Et on met à jour la racine.
            var nouvelleRacine = racine.ReplaceNode(type, nouveauType);

            return document.WithSyntaxRoot(nouvelleRacine);
        }
开发者ID:JabX,项目名称:controle-point-virgule,代码行数:39,代码来源:Correcteur.cs


示例3: GetNewFilePath

 private static string GetNewFilePath(Document document, TypeDeclarationSyntax declaration)
 {
     var oldFilePath = document.FilePath;
     var oldFileDirectory = Path.GetDirectoryName(document.FilePath);
     var newFilePath = Path.Combine(oldFileDirectory, declaration.Identifier.Text + ".cs");
     return newFilePath;
 }
开发者ID:GrahamTheCoder,项目名称:RoslynSpike,代码行数:7,代码来源:CodeFixProvider.cs


示例4: GetContainingTypeName

		private static IEnumerable<string> GetContainingTypeName(TypeDeclarationSyntax syntax)
		{
			for (var typeDeclaration = syntax; typeDeclaration != null; typeDeclaration = typeDeclaration.Parent as TypeDeclarationSyntax)
			{
				yield return typeDeclaration.Identifier.ValueText;
			}
		}
开发者ID:henrylle,项目名称:ArchiMetrics,代码行数:7,代码来源:TypeExtensions.cs


示例5: AddDisposeDeclarationToDisposeMethod

 private static TypeDeclarationSyntax AddDisposeDeclarationToDisposeMethod(VariableDeclaratorSyntax variableDeclarator, TypeDeclarationSyntax type, INamedTypeSymbol typeSymbol)
 {
     var disposableMethod = typeSymbol.GetMembers("Dispose").OfType<IMethodSymbol>().FirstOrDefault(d => d.Arity == 0);
     var disposeStatement = SyntaxFactory.ParseStatement($"{variableDeclarator.Identifier.ToString()}.Dispose();");
     TypeDeclarationSyntax newType;
     if (disposableMethod == null)
     {
         var disposeMethod = SyntaxFactory.MethodDeclaration(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)), "Dispose")
               .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
               .WithBody(SyntaxFactory.Block(disposeStatement))
               .WithAdditionalAnnotations(Formatter.Annotation);
         newType = ((dynamic)type).AddMembers(disposeMethod);
     }
     else
     {
         var existingDisposeMethod = (MethodDeclarationSyntax)disposableMethod.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax();
         if (type.Members.Contains(existingDisposeMethod))
         {
             var newDisposeMethod = existingDisposeMethod.AddBodyStatements(disposeStatement)
                 .WithAdditionalAnnotations(Formatter.Annotation);
             newType = type.ReplaceNode(existingDisposeMethod, newDisposeMethod);
         }
         else
         {
             //we will simply anotate the code for now, but ideally we would change another document
             //for this to work we have to be able to fix more than one doc
             var fieldDeclaration = variableDeclarator.Parent.Parent;
             var newFieldDeclaration = fieldDeclaration.WithTrailingTrivia(SyntaxFactory.ParseTrailingTrivia($"//add {disposeStatement.ToString()} to the Dispose method on another file.").AddRange(fieldDeclaration.GetTrailingTrivia()))
                 .WithLeadingTrivia(fieldDeclaration.GetLeadingTrivia());
             newType = type.ReplaceNode(fieldDeclaration, newFieldDeclaration);
         }
     }
     return newType;
 }
开发者ID:haroldhues,项目名称:code-cracker,代码行数:34,代码来源:DisposableFieldNotDisposedCodeFixProvider.cs


示例6: ClassStructDeclarationTranslation

 public ClassStructDeclarationTranslation(TypeDeclarationSyntax syntax, SyntaxTranslation parent) : base(syntax, parent)
 {
     if (syntax.BaseList != null)
     {
         BaseList = syntax.BaseList.Get<BaseListTranslation>(this);                
     }           
 }
开发者ID:asthomas,项目名称:TypescriptSyntaxPaste,代码行数:7,代码来源:ClassStructDeclarationTranslation.cs


示例7: GetPossibleStaticMethods

		public IEnumerable<MethodDeclarationSyntax> GetPossibleStaticMethods(TypeDeclarationSyntax type)
		{
			return type.DescendantNodes()
				.OfType<MethodDeclarationSyntax>()
				.Where(x => !x.Modifiers.Any(SyntaxKind.StaticKeyword))
				.Where(CanBeMadeStatic)
				.AsArray();
		}
开发者ID:jjrdk,项目名称:ArchiMetrics,代码行数:8,代码来源:SemanticAnalyzer.cs


示例8: AddType

        public static void AddType(this Scope scope, TypeDeclarationSyntax type)
        {
            var types = scope.find<List<TypeDeclarationSyntax>>("__additionalTypes");
            if (types == null)
                throw new InvalidOperationException("document scope not initialized");

            types.Add(type);
        }
开发者ID:mpmedia,项目名称:Excess,代码行数:8,代码来源:Scope.cs


示例9: AnalyzeType

 private void AnalyzeType(SyntaxTreeAnalysisContext context, TypeDeclarationSyntax typeDeclaration)
 {
     var numberOfFields = typeDeclaration.Members.Count(member => member is FieldDeclarationSyntax);
     if (numberOfFields > MaximumNumberOfFields)
     {
         context.ReportDiagnostic(Diagnostic.Create(Rule, typeDeclaration.Identifier.GetLocation(), typeDeclaration.Identifier.Text, numberOfFields));
     }
 }
开发者ID:johannes-schmitt,项目名称:DaVinci,代码行数:8,代码来源:Oc8NoClassesWithMoreThanTwoFields.cs


示例10: TypeDeclarationCompiles

 internal static bool TypeDeclarationCompiles(TypeDeclarationSyntax generatedType)
 {
     var newTypes = new List<TypeDeclarationSyntax>();
     newTypes.Add(generatedType);
     var tree = GetTestSyntaxTreeWithTypes(newTypes);
     var compilation = CreateCompilation(tree);
     var diags = compilation.GetDiagnostics();
     return !diags.Any(diag => diag.Severity == DiagnosticSeverity.Error);
 }
开发者ID:CodeConnect,项目名称:SyntaxFactoryVsParseText,代码行数:9,代码来源:TestHelpers.cs


示例11: MoveToMatchingFileAsync

 private async Task<Solution> MoveToMatchingFileAsync(Document document, SyntaxNode syntaxTree, TypeDeclarationSyntax declaration, CancellationToken cancellationToken)
 {
     var otherTypeDeclarationsInFile = syntaxTree.DescendantNodes().Where(originalNode => TypeDeclarationOtherThan(declaration, originalNode)).ToList();
     string newFilePath = GetNewFilePath(document, declaration);
     var newDocumentSyntaxTree = GetNewDocumentSyntaxTree(syntaxTree, otherTypeDeclarationsInFile);
     var newFile = document.Project.AddDocument(newFilePath, newDocumentSyntaxTree.GetText(), document.Folders);
     var solutionWithClassRemoved = GetDocumentWithClassDeclarationRemoved(newFile.Project, document, syntaxTree, declaration, otherTypeDeclarationsInFile);
     
     return document.Project.RemoveDocument(document.Id).Solution;
 }
开发者ID:GrahamTheCoder,项目名称:RoslynSpike,代码行数:10,代码来源:CodeFixProvider.cs


示例12: DetermineClassType

 private ClassType DetermineClassType(TypeDeclarationSyntax declaration)
 {
     if (declaration.Keyword.RawKind == InterfaceKeywordToken) return ClassType.Other;
     var isDataStructure = HasPublicProperties(declaration) || HasPublicFields(declaration);
     var isObject = HasMethods(declaration);
     if (isDataStructure && isObject && HasNotOnlyConstOrReadonlyFields(declaration)) return ClassType.Hybrid;
     if (isObject) return ClassType.Object;
     if (isDataStructure) return ClassType.DataStructure;
     return ClassType.Other;
 }
开发者ID:birksimon,项目名称:CodeAnalysis,代码行数:10,代码来源:ObjectAndDatastructureValidator.cs


示例13: ExpandType

        private static TypeDeclarationSyntax ExpandType(TypeDeclarationSyntax original, TypeDeclarationSyntax updated, IEnumerable<ExpandablePropertyInfo> properties, SemanticModel model, Workspace workspace)
        {
            Debug.Assert(original != updated);

            return updated
                .WithBackingFields(properties, workspace)
                .WithBaseType(original, model)
                .WithPropertyChangedEvent(original, model, workspace)
                .WithSetPropertyMethod(original, model, workspace);
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:10,代码来源:CodeGeneration.cs


示例14: MakeInterface

 private static InterfaceDeclarationSyntax MakeInterface(TypeDeclarationSyntax typeSyntax)
 {
     return SyntaxFactory.InterfaceDeclaration(
         attributeLists: typeSyntax.AttributeLists,
         modifiers: typeSyntax.Modifiers,
         identifier: typeSyntax.Identifier,
         typeParameterList: typeSyntax.TypeParameterList,
         baseList: typeSyntax.BaseList,
         constraintClauses: typeSyntax.ConstraintClauses,
         members: MakeInterfaceSyntaxList(typeSyntax.Members)).NormalizeWhitespace();
 }
开发者ID:nhabuiduc,项目名称:TypescriptSyntaxPaste,代码行数:11,代码来源:ClassToInterfaceReplacement.cs


示例15: AddConversionTo

        internal static TypeDeclarationSyntax AddConversionTo(
            TypeDeclarationSyntax destination,
            IMethodSymbol method,
            CodeGenerationOptions options,
            IList<bool> availableIndices)
        {
            var methodDeclaration = GenerateConversionDeclaration(method, GetDestination(destination), options);

            var members = Insert(destination.Members, methodDeclaration, options, availableIndices, after: LastOperator);

            return AddMembersTo(destination, members);
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:12,代码来源:ConversionGenerator.cs


示例16: AddNamedTypeTo

        public static TypeDeclarationSyntax AddNamedTypeTo(
            ICodeGenerationService service,
            TypeDeclarationSyntax destination,
            INamedTypeSymbol namedType,
            CodeGenerationOptions options,
            IList<bool> availableIndices)
        {
            var declaration = GenerateNamedTypeDeclaration(service, namedType, GetDestination(destination), options);
            var members = Insert(destination.Members, declaration, options, availableIndices);

            return AddMembersTo(destination, members);
        }
开发者ID:GloryChou,项目名称:roslyn,代码行数:12,代码来源:NamedTypeGenerator.cs


示例17: AddMethodTo

        internal static TypeDeclarationSyntax AddMethodTo(
            TypeDeclarationSyntax destination,
            IMethodSymbol method,
            CodeGenerationOptions options,
            IList<bool> availableIndices)
        {
            var methodDeclaration = GenerateMethodDeclaration(method, GetDestination(destination), options);

            // Create a clone of the original type with the new method inserted. 
            var members = Insert(destination.Members, methodDeclaration, options, availableIndices, after: LastMethod);

            return AddMembersTo(destination, members);
        }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:13,代码来源:MethodGenerator.cs


示例18: ReplaceModifiers

        // This code was copied from the Roslyn code base (and slightly modified). It can be removed if
        // TypeDeclarationSyntaxExtensions.WithModifiers is made public (Roslyn issue #2186)
        private static TypeDeclarationSyntax ReplaceModifiers(TypeDeclarationSyntax node, SyntaxTokenList modifiers)
        {
            switch (node.Kind())
            {
            case SyntaxKind.ClassDeclaration:
                return ((ClassDeclarationSyntax)node).WithModifiers(modifiers);
            case SyntaxKind.InterfaceDeclaration:
                return ((InterfaceDeclarationSyntax)node).WithModifiers(modifiers);
            case SyntaxKind.StructDeclaration:
                return ((StructDeclarationSyntax)node).WithModifiers(modifiers);
            }

            return node;
        }
开发者ID:Noryoko,项目名称:StyleCopAnalyzers,代码行数:16,代码来源:SA1205CodeFixProvider.cs


示例19: AddIDisposableImplementationToType

 private static TypeDeclarationSyntax AddIDisposableImplementationToType(TypeDeclarationSyntax type, INamedTypeSymbol typeSymbol)
 {
     var iDisposableInterface = typeSymbol.AllInterfaces.FirstOrDefault(i => i.ToString() == "System.IDisposable");
     if (iDisposableInterface != null) return type;
     var newBaseList = type.BaseList != null
         ? type.BaseList.AddTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseName("System.IDisposable").WithAdditionalAnnotations(Simplifier.Annotation)))
         : SyntaxFactory.BaseList(SyntaxFactory.SeparatedList(new BaseTypeSyntax[] {
                 SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseName("System.IDisposable").WithAdditionalAnnotations(Simplifier.Annotation)) }));
     TypeDeclarationSyntax newType = ((dynamic)type)
         .WithBaseList(newBaseList)
         .WithIdentifier(SyntaxFactory.Identifier(type.Identifier.Text));//this line is stupid, it is here only to remove the line break at the end of the identifier that roslyn for some reason puts there
     newType = newType.WithAdditionalAnnotations(Formatter.Annotation);//can't chain because this would be an ext.method on a dynamic type
     return newType;
 }
开发者ID:haroldhues,项目名称:code-cracker,代码行数:14,代码来源:DisposableFieldNotDisposedCodeFixProvider.cs


示例20: TryReplaceTypeMembers

 private static bool TryReplaceTypeMembers(TypeDeclarationSyntax typeDeclarationSyntax, IEnumerable<MemberDeclarationSyntax> membersDeclaration, IEnumerable<MemberDeclarationSyntax> sortedMembers, out TypeDeclarationSyntax orderedType)
 {
     var sortedMembersQueue = new Queue<MemberDeclarationSyntax>(sortedMembers);
     var orderChanged = false;
     orderedType = typeDeclarationSyntax.ReplaceNodes(
         membersDeclaration,
         (original, rewritten) =>
         {
             var newMember = sortedMembersQueue.Dequeue();
             if (!orderChanged && !original.Equals(newMember)) orderChanged = true;
             return newMember;
         });
     return orderChanged;
 }
开发者ID:haroldhues,项目名称:code-cracker,代码行数:14,代码来源:AllowMembersOrderingCodeFixProvider.Base.cs



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Syntax.TypeSyntax类代码示例发布时间:2022-05-26
下一篇:
C# Syntax.SyntaxList类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap