當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。