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


C# IMethodSymbol.GetAttributes方法代码示例

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


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

示例1: GenerateConversionDeclarationWorker

        private static ConversionOperatorDeclarationSyntax GenerateConversionDeclarationWorker(
            IMethodSymbol method,
            CodeGenerationDestination destination,
            CodeGenerationOptions options)
        {
            var hasNoBody = !options.GenerateMethodBodies || method.IsExtern;

            var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ConversionOperatorDeclarationSyntax>(method, options);
            if (reusableSyntax != null)
            {
                return reusableSyntax;
            }

            var operatorToken = SyntaxFactory.Token(SyntaxFacts.GetOperatorKind(method.MetadataName));
            var keyword = method.MetadataName == WellKnownMemberNames.ImplicitConversionName
                ? SyntaxFactory.Token(SyntaxKind.ImplicitKeyword)
                : SyntaxFactory.Token(SyntaxKind.ExplicitKeyword);

            return SyntaxFactory.ConversionOperatorDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options),
                modifiers: GenerateModifiers(method),
                implicitOrExplicitKeyword: keyword,
                operatorKeyword: SyntaxFactory.Token(SyntaxKind.OperatorKeyword),
                type: method.ReturnType.GenerateTypeSyntax(),
                parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options: options),
                body: hasNoBody ? null : StatementGenerator.GenerateBlock(method),
                semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : new SyntaxToken());
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:28,代码来源:ConversionGenerator.cs

示例2: MarkedWithStringFormatMethodAttribute

 private static bool MarkedWithStringFormatMethodAttribute(IMethodSymbol method)
 {
     return 
         method.GetAttributes()
         .Select(a => a.AttributeClass.FullName())
         .Any(a => a == "JetBrains.Annotations.StringFormatMethodAttribute");
 }
开发者ID:SergeyTeplyakov,项目名称:ErrorProne.NET,代码行数:7,代码来源:FormatHelper.cs

示例3: GenerateOperatorDeclarationWorker

        private static OperatorDeclarationSyntax GenerateOperatorDeclarationWorker(
            IMethodSymbol method,
            CodeGenerationDestination destination,
            CodeGenerationOptions options)
        {
            var hasNoBody = !options.GenerateMethodBodies || method.IsExtern;

            var operatorSyntaxKind = SyntaxFacts.GetOperatorKind(method.MetadataName);
            if (operatorSyntaxKind == SyntaxKind.None)
            {
                throw new ArgumentException(string.Format(WorkspacesResources.Cannot_generate_code_for_unsupported_operator_0, method.Name), nameof(method));
            }

            var operatorToken = SyntaxFactory.Token(operatorSyntaxKind);

            return SyntaxFactory.OperatorDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options),
                modifiers: GenerateModifiers(method),
                returnType: method.ReturnType.GenerateTypeSyntax(),
                operatorKeyword: SyntaxFactory.Token(SyntaxKind.OperatorKeyword),
                operatorToken: operatorToken,
                parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options: options),
                body: hasNoBody ? null : StatementGenerator.GenerateBlock(method),
                semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : new SyntaxToken());
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:25,代码来源:OperatorGenerator.cs

示例4: GenerateConstructorDeclaration

        internal static ConstructorDeclarationSyntax GenerateConstructorDeclaration(
            IMethodSymbol constructor, CodeGenerationDestination destination, CodeGenerationOptions options)
        {
            options = options ?? CodeGenerationOptions.Default;

            var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ConstructorDeclarationSyntax>(constructor, options);
            if (reusableSyntax != null)
            {
                return reusableSyntax;
            }

            bool hasNoBody = !options.GenerateMethodBodies;

            var declaration = SyntaxFactory.ConstructorDeclaration(
                attributeLists: AttributeGenerator.GenerateAttributeLists(constructor.GetAttributes(), options),
                modifiers: GenerateModifiers(constructor, options),
                identifier: CodeGenerationConstructorInfo.GetTypeName(constructor).ToIdentifierToken(),
                parameterList: ParameterGenerator.GenerateParameterList(constructor.Parameters, isExplicit: false, options: options),
                initializer: GenerateConstructorInitializer(constructor),
                body: hasNoBody ? null : GenerateBlock(constructor),
                semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : default(SyntaxToken));

            return AddCleanupAnnotationsTo(
                ConditionallyAddDocumentationCommentTo(declaration, constructor, options));
        }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:25,代码来源:ConstructorGenerator.cs

示例5: GenerateAttributes

        private static SyntaxList<AttributeListSyntax> GenerateAttributes(
            IMethodSymbol method, CodeGenerationOptions options, bool isExplicit)
        {
            var attributes = new List<AttributeListSyntax>();

            if (!isExplicit)
            {
                attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options));
                attributes.AddRange(AttributeGenerator.GenerateAttributeLists(method.GetReturnTypeAttributes(), options, SyntaxFactory.Token(SyntaxKind.ReturnKeyword)));
            }

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

示例6: ContainsHandleProcessCorruptedStateExceptionsAttribute

 private bool ContainsHandleProcessCorruptedStateExceptionsAttribute(IMethodSymbol method, CompilationSecurityTypes compilationTypes)
 {
     ImmutableArray<AttributeData> attributes = method.GetAttributes();
     return attributes.Any(
         attribute => attribute.AttributeClass.Equals(compilationTypes.HandleProcessCorruptedStateExceptionsAttribute));
 }
开发者ID:bkoelman,项目名称:roslyn-analyzers,代码行数:6,代码来源:DoNotCatchCorruptedStateExceptions.cs

示例7: MethodCanBeSafelyChanged

 private static bool MethodCanBeSafelyChanged(IMethodSymbol methodSymbol)
 {
     return methodSymbol.DeclaredAccessibility == Accessibility.Private &&
         !methodSymbol.GetAttributes().Any() &&
         methodSymbol.IsChangeable() &&
         !methodSymbol.IsProbablyEventHandler();
 }
开发者ID:dbolkensteyn,项目名称:sonarlint-vs,代码行数:7,代码来源:MethodParameterUnused.cs

示例8: GenerateProtocolCode


//.........这里部分代码省略.........
		//			}
		//		
		//			return result;
		//		}
		//		
		//		static bool InsertUsingAfter (AstNode node)
		//		{
		//			return node is NewLineNode && IsCommentOrUsing (node.GetNextSibling (s => !(s is NewLineNode))) ||
		//				IsCommentOrUsing (node) || (node is PreProcessorDirective);
		//		}
		//
		//		static bool IsCommentOrUsing (AstNode node)
		//		{
		//			return node is ICSharpCode.NRefactory.CSharp.Comment ||
		//				node is UsingDeclaration ||
		//				node is UsingAliasDeclaration;
		//		}
		//		

		//		
		//		static string OutputNode (TextEditor editor, DocumentContext context, AstNode node)
		//		{
		//			using (var stringWriter = new System.IO.StringWriter ()) {
		////				formatter.Indentation = indentLevel;
		//				var formatter = new TextWriterTokenWriter (stringWriter);
		//				stringWriter.NewLine = editor.EolMarker;
		//
		//				var visitor = new CSharpOutputVisitor (formatter, null /* TODO: BROKEN DUE ROSLYN PORT (note: that code should be unused) */ );
		//				node.AcceptVisitor (visitor);
		//				return stringWriter.ToString ();
		//			}
		//		}
		//		
		//		
		//		public AstType CreateShortType (ICompilation compilation, CSharpUnresolvedFile parsedFile, TextLocation loc, IType fullType)
		//		{
		//			var csResolver = parsedFile.GetResolver (compilation, loc);
		//			var builder = new ICSharpCode.NRefactory.CSharp.Refactoring.TypeSystemAstBuilder (csResolver);
		//			return builder.ConvertType (fullType);			
		//		}
		//		
		//		public override void CompleteStatement (MonoDevelop.Ide.Gui.Document doc)
		//		{
		//			//  TODO: BROKEN DUE ROSLYN PORT - needs to be ported to NR6
		////			var fixer = new ConstructFixer (doc.GetFormattingOptions (), doc.Editor.CreateNRefactoryTextEditorOptions ());
		////			int newOffset;
		////			if (fixer.TryFix (new DocumentWrapper (doc.Editor), doc.Editor.CaretOffset, out newOffset)) {
		////				doc.Editor.CaretOffset = newOffset;
		////			}
		//		}




		static CodeGeneratorMemberResult GenerateProtocolCode(IMethodSymbol method, CodeGenerationOptions options)
		{
			int bodyStartOffset = -1, bodyEndOffset = -1;
			var result = new StringBuilder();
			var exportAttribute = method.GetAttributes ().FirstOrDefault (attr => attr.AttributeClass.Name == "ExportAttribute");
			if (exportAttribute != null) {
				result.Append ("[Export(\"");
				result.Append (exportAttribute.ConstructorArguments.First ().Value.ToString ());
				result.Append ("\")]");
				result.AppendLine ();
			}
			AppendModifiers (result, options, method);

			AppendReturnType (result, options, method.ReturnType);
			result.Append (" ");
			if (options.ExplicitDeclaration) {
				AppendReturnType (result, options, method.ContainingType);
				result.Append(".");
			}

			result.Append(CSharpAmbience.FilterName(method.Name));
			if (method.TypeParameters.Length > 0) {
				result.Append("<");
				for (int i = 0; i < method.TypeParameters.Length; i++) {
					if (i > 0)
						result.Append(", ");
					var p = method.TypeParameters[i];
					result.Append(CSharpAmbience.FilterName(p.Name));
				}
				result.Append(">");
			}
			result.Append("(");
			AppendParameterList (result, options, method.Parameters, true);
			result.Append(")");

			var typeParameters = method.TypeParameters;

			result.Append ("{");
			AppendIndent (result);
			bodyStartOffset = result.Length;
			result.Append ("throw new System.NotImplementedException ();");
			bodyEndOffset = result.Length;
			AppendLine (result);
			result.Append ("}");
			return new CodeGeneratorMemberResult(result.ToString (), bodyStartOffset, bodyEndOffset);
		}
开发者ID:zenek-y,项目名称:monodevelop,代码行数:101,代码来源:CSharpCodeGenerator.cs

示例9: TranslateMethodAttributes

      private TemplateEventMethodInfo TranslateMethodAttributes(IMethodSymbol sourceMethod, EventSourceTypeInfo eventSourceTypeInfo, CollectedGenerationInfo overloads)
      {
         List<SyntaxNode> attributes = new List<SyntaxNode>();

         SyntaxNode eventAttribute = null;
         int? eventId = null;

         foreach (AttributeData attributeData in sourceMethod.GetAttributes())
         {
            var attributeClass = attributeData.AttributeClass;

            if (attributeClass.Name.Equals(TemplateEventAttributeName) || attributeClass.Equals(eventSourceTypeInfo.EventAttributeType))
            {               
               SyntaxNode attributeSyntax = attributeData.ApplicationSyntaxReference?.GetSyntax();
               if (attributeSyntax == null)
                  throw new CodeGeneratorException(sourceMethod, $"Cannot find the source file containing the method {sourceMethod.Name}. The source code must be available for any Template EventSource class to participate in generation. Is the project unloaded?");

               Document attributeDocument = m_document.Project.Solution.GetDocument(attributeSyntax.SyntaxTree);
               if (attributeDocument == null)
                  throw new CodeGeneratorException(sourceMethod, $"Cannot find the document containing the method {sourceMethod.Name}.");

               
               overloads.AddConstants(attributeSyntax, attributeDocument.GetSemanticModelAsync().Result, eventSourceTypeInfo);

               attributeSyntax = m_generator.Attribute(eventSourceTypeInfo.EventAttributeType.GetFullName(), m_generator.GetAttributeArguments(attributeSyntax));
                  
               attributes.Add(attributeSyntax);


               TypedConstant eventIdArgument = attributeData.ConstructorArguments.FirstOrDefault();
               if (attributeData.ConstructorArguments.Length == 0)
                  throw new CodeGeneratorException(sourceMethod, $"The {attributeData.AttributeClass.Name} attribute must have an event ID as its first argument.");

               if (!(eventIdArgument.Value is int))
                  throw new CodeGeneratorException(sourceMethod, $"The first argument to the {attributeData.AttributeClass.Name} attribute must be of type Int32.");

               eventId = (int)eventIdArgument.Value;
               eventAttribute = attributeSyntax;
            }
            else
            {
               attributes.Add(CreateAttribute(attributeData));                  
            }
         }

         if (eventAttribute == null)
            throw new CodeGeneratorException(sourceMethod, $"Internal error; Unable to find EventAttribute or TemplateEventAttribute on method {sourceMethod.Name}");

         if (eventId == null)
            throw new CodeGeneratorException(sourceMethod, $"Unable to determine EventId for method {sourceMethod.Name}");

         return new TemplateEventMethodInfo(attributes, eventId.Value);
      }
开发者ID:modulexcite,项目名称:EventSourceGenerator-1,代码行数:53,代码来源:EventSourceGenerator.cs

示例10: GetCommandInfo

 CommandInfo GetCommandInfo(IMethodSymbol method)
 {
     return method.GetAttributes()
                 .FirstOrDefault(x => x.AttributeClass == asyncCommandAttributeType || x.AttributeClass == commandAttributeType)
                 .With(x => {
                     var args = x.ConstructorArguments.Select(arg => arg.Value).ToArray(); //TODO dup code
                     var namedArgs = x.NamedArguments.ToImmutableDictionary(p => p.Key, p => p.Value.Value); //TODO error if names are not recognizable
                     return new CommandInfo(
                         isCommand: args.Length > 0 ? (bool)args[0] : true,
                         allowMultipleExecution: (bool)namedArgs.GetValueOrDefault("AllowMultipleExecution", false),
                         useCommandManager: (bool)namedArgs.GetValueOrDefault("UseCommandManager", true),
                         name: (string)namedArgs.GetValueOrDefault("Name"),
                         canExecuteMethodName: (string)namedArgs.GetValueOrDefault("CanExecuteMethodName"));
                 });
 }
开发者ID:VitalyTVA,项目名称:MetaSharp,代码行数:15,代码来源:ViewModelCompleter.cs

示例11: ShouldAnalyze

        private static bool ShouldAnalyze(IMethodSymbol methodSymbol, Compilation compilation)
        {
            // Modifiers that we don't care about
            if (methodSymbol.IsStatic || methodSymbol.IsOverride || methodSymbol.IsVirtual ||
                methodSymbol.IsExtern || methodSymbol.IsAbstract || methodSymbol.IsImplementationOfAnyInterfaceMember())
            {
                return false;
            }

            if (methodSymbol.IsConstructor() || methodSymbol.IsFinalizer())
            {
                return false;
            }
            
            // CA1000 says one shouldn't declare static members on generic types. So don't flag such cases.
            if (methodSymbol.ContainingType.IsGenericType && methodSymbol.GetResultantVisibility() == SymbolVisibility.Public)
            {
                return false;
            }

            // FxCop doesn't check for the fully qualified name for these attributes - so we'll do the same.
            var skipAttributes = new[]
            {
                "WebMethodAttribute",
                "TestInitializeAttribute",
                "TestMethodAttribute",
                "TestCleanupAttribute",
            };

            if (methodSymbol.GetAttributes().Any(attribute => skipAttributes.Contains(attribute.AttributeClass.Name)))
            {
                return false;
            }

            // If this looks like an event handler don't flag such cases.
            if (methodSymbol.Parameters.Length == 2 && 
                methodSymbol.Parameters[0].Type.SpecialType == SpecialType.System_Object &&
                IsEventArgs(methodSymbol.Parameters[1].Type, compilation))
            {
                return false;
            }

            if (IsExplicitlyVisibleFromCom(methodSymbol, compilation))
            {
                return false;
            }

            return true;
        }
开发者ID:duracellko,项目名称:roslyn-analyzers,代码行数:49,代码来源:MarkMembersAsStatic.cs

示例12: IsExplicitlyVisibleFromCom

        private static bool IsExplicitlyVisibleFromCom(IMethodSymbol methodSymbol, Compilation compilation)
        {
            if (methodSymbol.GetResultantVisibility() != SymbolVisibility.Public || methodSymbol.IsGenericMethod)
            {
                return false;
            }

            var comVisibleAttribute = WellKnownTypes.ComVisibleAttribute(compilation);
            if (comVisibleAttribute == null)
            {
                return false;
            }

            if (methodSymbol.GetAttributes().Any(attribute => attribute.AttributeClass.Equals(comVisibleAttribute)) ||
                methodSymbol.ContainingType.GetAttributes().Any(attribute => attribute.AttributeClass.Equals(comVisibleAttribute)))
            {
                return true;
            }

            return false;
        }
开发者ID:duracellko,项目名称:roslyn-analyzers,代码行数:21,代码来源:MarkMembersAsStatic.cs

示例13: GetFormatArgumentName

        // TODO: analyze not only with format litteral but with method calls that returns formatted literal!
        private static string GetFormatArgumentName(IMethodSymbol symbol)
        {
            var annotationAttribute = symbol.GetAttributes().FirstOrDefault(a => a.AttributeClass.FullName() == "JetBrains.Annotations.StringFormatMethodAttribute");
            if (annotationAttribute != null)
            {
                var firstArgument = annotationAttribute.ConstructorArguments.FirstOrDefault();
                if (firstArgument.Value != null)
                {
                    return firstArgument.Value.ToString();
                }
            }

            return expectedFormatArgumentName;
        }
开发者ID:SergeyTeplyakov,项目名称:ErrorProne.NET,代码行数:15,代码来源:FormatHelper.cs

示例14: GetAttributeArgument

        private static string GetAttributeArgument(IMethodSymbol methodSymbol, string typeName)
        {
            var attribute = methodSymbol.GetAttributes().FirstOrDefault(a => a.ToString().Contains(typeName));
            if (attribute != null)
            {
                return attribute.ConstructorArguments.First().Value.ToString();
            }

            throw new Exception("Unable to retrieve/parse attribute parameters.");
        }
开发者ID:lukeautry,项目名称:DotNetWebSDK,代码行数:10,代码来源:SourceFileProcessor.cs

示例15: TryGetOperationContract

        private static bool TryGetOperationContract(IMethodSymbol methodSymbol, out AttributeData attribute)
        {
            attribute = methodSymbol.GetAttributes()
                .FirstOrDefault(a => a.AttributeClass.Is(KnownType.System_ServiceModel_OperationContractAttribute));

            return attribute != null;
        }
开发者ID:duncanpMS,项目名称:sonarlint-vs,代码行数:7,代码来源:WcfNonVoidOneWay.cs


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