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


C# Syntax.TypeDeclarationSyntax类代码示例

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


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


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