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


C# SemanticModel.GetEnclosingSymbol方法代码示例

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


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

示例1: TryDetermineOverridableMembers

		static bool TryDetermineOverridableMembers(SemanticModel semanticModel, SyntaxToken startToken, Accessibility seenAccessibility, out ISet<ISymbol> overridableMembers, CancellationToken cancellationToken)
		{
			var result = new HashSet<ISymbol>();
			var containingType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(startToken.SpanStart, cancellationToken);
			if (containingType != null && !containingType.IsScriptClass && !containingType.IsImplicitClass)
			{
				if (containingType.TypeKind == TypeKind.Class || containingType.TypeKind == TypeKind.Struct)
				{
					var baseTypes = containingType.GetBaseTypes().Reverse();
					foreach (var type in baseTypes)
					{
						cancellationToken.ThrowIfCancellationRequested();

						// Prefer overrides in derived classes
						RemoveOverriddenMembers(result, type, cancellationToken);

						// Retain overridable methods
						AddProtocolMembers(semanticModel, result, containingType, type, cancellationToken);
					}
					// Don't suggest already overridden members
					RemoveOverriddenMembers(result, containingType, cancellationToken);
				}
			}

			// Filter based on accessibility
			if (seenAccessibility != Accessibility.NotApplicable)
			{
				result.RemoveWhere(m => m.DeclaredAccessibility != seenAccessibility);
			}

			overridableMembers = result;
			return overridableMembers.Count > 0;
		}
开发者ID:pabloescribanoloza,项目名称:monodevelop,代码行数:33,代码来源:ProtocolMemberContextHandler.cs

示例2: IsAssignmentOutsideConstructor

 private static bool IsAssignmentOutsideConstructor(AssignmentExpressionSyntax assignment, ISymbol fieldSymbol, SemanticModel model)
 {
     var assignedSymbol = model.GetSymbolInfo(assignment.Left);
     if (assignedSymbol.Symbol != fieldSymbol)
     {
         return false;
     }
     // Method (or whatever) enclosing the assignment
     var enclosingSymbol = model.GetEnclosingSymbol(assignment.SpanStart) as IMethodSymbol;
     var isCtor = enclosingSymbol?.MethodKind == MethodKind.Constructor;
     return !isCtor;
 }
开发者ID:njannink,项目名称:sonarlint-vs,代码行数:12,代码来源:ReadWriteForEfficiencyDiagnosticAnalyzer.cs

示例3: CreateCompletionData

		protected override IEnumerable<CompletionData> CreateCompletionData (CompletionEngine engine, SemanticModel semanticModel, int position, ITypeSymbol returnType, Accessibility seenAccessibility, SyntaxToken startToken, SyntaxToken tokenBeforeReturnType, bool afterKeyword, CancellationToken cancellationToken)
		{
			var result = new List<CompletionData> ();
			ISet<ISymbol> overridableMembers;
			if (!TryDetermineOverridableMembers (semanticModel, tokenBeforeReturnType, seenAccessibility, out overridableMembers, cancellationToken)) {
				return result;
			}
			if (returnType != null) {
				overridableMembers = FilterOverrides (overridableMembers, returnType);
			}
			var curType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol> (startToken.SpanStart, cancellationToken);
			var declarationBegin = afterKeyword ? startToken.SpanStart : position - 1;
			foreach (var m in overridableMembers) {
				var data = new ProtocolCompletionData (this, factory, declarationBegin, curType, m, afterKeyword);
				result.Add (data);
			}
			return result;
		}
开发者ID:pabloescribanoloza,项目名称:monodevelop,代码行数:18,代码来源:ProtocolMemberContextHandler.cs

示例4: IsBinaryCandidateForReporting

        private static bool IsBinaryCandidateForReporting(BinaryExpressionSyntax binary, SemanticModel semanticModel)
        {
            var equalitySymbol = semanticModel.GetSymbolInfo(binary).Symbol as IMethodSymbol;

            return equalitySymbol.IsInType(KnownType.System_Object) &&
                !IsInEqualsOverride(semanticModel.GetEnclosingSymbol(binary.SpanStart) as IMethodSymbol);
        }
开发者ID:dbolkensteyn,项目名称:sonarlint-vs,代码行数:7,代码来源:ReferenceEqualityCheckWhenEqualsExists.cs

示例5: GetLambdaExpressionSymbol

 internal override IMethodSymbol GetLambdaExpressionSymbol(SemanticModel model, SyntaxNode lambdaExpression, CancellationToken cancellationToken)
 {
     return (IMethodSymbol)model.GetEnclosingSymbol(lambdaExpression.SpanStart, cancellationToken);
 }
开发者ID:GeertVL,项目名称:roslyn,代码行数:4,代码来源:CSharpEditAndContinueAnalyzer.cs

示例6: GetReturnedSymbols

        private static ImmutableHashSet<ISymbol> GetReturnedSymbols(StatementSyntax usingStatement,
            SemanticModel semanticModel)
        {
            var enclosingSymbol = semanticModel.GetEnclosingSymbol(usingStatement.SpanStart);

            return usingStatement.DescendantNodesAndSelf()
                .OfType<ReturnStatementSyntax>()
                .Where(ret => semanticModel.GetEnclosingSymbol(ret.SpanStart).Equals(enclosingSymbol))
                .Select(ret => ret.Expression)
                .OfType<IdentifierNameSyntax>()
                .Select(identifier => semanticModel.GetSymbolInfo(identifier).Symbol)
                .Where(symbol => symbol != null)
                .ToImmutableHashSet();
        }
开发者ID:Thejas007,项目名称:sonarlint-vs,代码行数:14,代码来源:DisposableReturnedFromUsing.cs

示例7: ProcessPropertyChange

        private static void ProcessPropertyChange(ExpressionSyntax expression, SemanticModel semanticModel,
            SyntaxNodeAnalysisContext context)
        {
            var memberAccess = expression as MemberAccessExpressionSyntax;
            if (memberAccess == null)
            {
                return;
            }

            var propertySymbol = semanticModel.GetSymbolInfo(expression).Symbol as IPropertySymbol;
            if (propertySymbol == null)
            {
                return;
            }

            var fieldSymbol = semanticModel.GetSymbolInfo(memberAccess.Expression).Symbol as IFieldSymbol;
            if (fieldSymbol == null ||
                !fieldSymbol.IsReadOnly ||
                !RelevantFieldType(fieldSymbol.Type))
            {
                return;
            }

            var constructorSymbol = semanticModel.GetEnclosingSymbol(expression.SpanStart) as IMethodSymbol;
            if (constructorSymbol != null &&
                constructorSymbol.MethodKind == MethodKind.Constructor &&
                constructorSymbol.ContainingType.Equals(fieldSymbol.ContainingType))
            {
                return;
            }

            context.ReportDiagnostic(Diagnostic.Create(Rule, expression.GetLocation(), fieldSymbol.Name, propertySymbol.Name));
        }
开发者ID:njannink,项目名称:sonarlint-vs,代码行数:33,代码来源:GenericReadonlyFieldPropertyAssignment.cs

示例8: GetIdentifierFieldMappings

 private static List<IdentifierFieldMapping> GetIdentifierFieldMappings(VariableDeclaratorSyntax variable,
     INamedTypeSymbol containingType, SemanticModel semanticModel)
 {
     return variable.Initializer.DescendantNodes()
         .OfType<IdentifierNameSyntax>()
         .Select(identifier =>
         {
             var field = semanticModel.GetSymbolInfo(identifier).Symbol as IFieldSymbol;
             var enclosingSymbol = semanticModel.GetEnclosingSymbol(identifier.SpanStart);
             return new IdentifierFieldMapping
             {
                 Identifier = identifier,
                 Field = field,
                 IsRelevant = field != null &&
                     field.IsStatic &&
                     containingType.Equals(field.ContainingType) &&
                     enclosingSymbol is IFieldSymbol &&
                     enclosingSymbol.ContainingType.Equals(field.ContainingType)
             };
         })
         .Where(identifier => identifier.IsRelevant)
         .ToList();
 }
开发者ID:njannink,项目名称:sonarlint-vs,代码行数:23,代码来源:StaticFieldInitializerOrder.cs

示例9: HandleInvocationExpression

		ParameterHintingResult HandleInvocationExpression(SemanticModel semanticModel, InvocationExpressionSyntax node, CancellationToken cancellationToken)
		{
			var info = semanticModel.GetSymbolInfo (node, cancellationToken);
			var result = new ParameterHintingResult(node.SpanStart);

			var targetTypeInfo = semanticModel.GetTypeInfo (node.Expression);
			if (targetTypeInfo.Type != null && targetTypeInfo.Type.TypeKind == TypeKind.Delegate) {
				result.AddData (factory.CreateMethodDataProvider (targetTypeInfo.Type.GetDelegateInvokeMethod ()));
				return result;
			}

			var within = semanticModel.GetEnclosingNamedTypeOrAssembly(node.SpanStart, cancellationToken);
			ITypeSymbol type;
			string name = null;
			bool staticLookup = false;
			var ma = node.Expression as MemberAccessExpressionSyntax;
			var mb = node.Expression as MemberBindingExpressionSyntax;
			if (mb != null) {
				info = semanticModel.GetSymbolInfo (mb, cancellationToken);
				type = (info.Symbol ?? info.CandidateSymbols.FirstOrDefault ())?.ContainingType;
				name = mb.Name.Identifier.ValueText;
			} else if (ma != null) {
				staticLookup = semanticModel.GetSymbolInfo (ma.Expression).Symbol is ITypeSymbol;
				type = semanticModel.GetTypeInfo (ma.Expression).Type;
				name = info.Symbol?.Name ?? ma.Name.Identifier.ValueText;
			} else {
				type = within as ITypeSymbol;
				name = info.Symbol?.Name ?? node.Expression.ToString ();
				var sym = semanticModel.GetEnclosingSymbol (node.SpanStart, cancellationToken); 
				staticLookup = sym.IsStatic;
			}
			var addedMethods = new List<IMethodSymbol> ();
			var filterMethod = new HashSet<IMethodSymbol> ();
			for (;type != null; type = type.BaseType) {
				foreach (var method in type.GetMembers ().OfType<IMethodSymbol> ().Concat (GetExtensionMethods(semanticModel, type, node, cancellationToken)).Where (m => m.Name == name)) {
					if (staticLookup && !method.IsStatic)
						continue;
					if (method.OverriddenMethod != null)
						filterMethod.Add (method.OverriddenMethod);
					if (filterMethod.Contains (method))
						continue;
					if (addedMethods.Any (added => SignatureComparer.HaveSameSignature (method, added, true)))
						continue;
					if (method.IsAccessibleWithin (within)) {
						if (info.Symbol != null) {
							var smethod = (IMethodSymbol)info.Symbol;
							if (smethod != null && smethod.OriginalDefinition == method) {
								continue;
							}
						}
						addedMethods.Add (method); 
						result.AddData (factory.CreateMethodDataProvider (method));
					}
				}
			}
			if (info.Symbol != null && !addedMethods.Contains (info.Symbol)) {
				if (!staticLookup || info.Symbol.IsStatic)
					result.AddData (factory.CreateMethodDataProvider ((IMethodSymbol)info.Symbol));
			}
			return result;
		}
开发者ID:pjcollins,项目名称:monodevelop,代码行数:61,代码来源:ParameterHintingEngine.cs

示例10: TryGetTypeFromReturnMappedToFloatType

        private static bool TryGetTypeFromReturnMappedToFloatType(BinaryExpressionSyntax division, SemanticModel semanticModel,
            out ITypeSymbol type)
        {
            if (division.Parent is ReturnStatementSyntax ||
                division.Parent is LambdaExpressionSyntax)
            {
                type = (semanticModel.GetEnclosingSymbol(division.SpanStart) as IMethodSymbol)?.ReturnType;
                return type.IsAny(KnownType.NonIntegralNumbers);
            }

            type = null;
            return false;
        }
开发者ID:dbolkensteyn,项目名称:sonarlint-vs,代码行数:13,代码来源:LossOfFractionInDivision.cs

示例11: IsCallInsideOverride

        private static bool IsCallInsideOverride(InvocationExpressionSyntax invocation, IMethodSymbol calledMethod,
            SemanticModel semanticModel)
        {
            var enclosingSymbol = semanticModel.GetEnclosingSymbol(invocation.SpanStart) as IMethodSymbol;

            return enclosingSymbol != null &&
                enclosingSymbol.IsOverride &&
                object.Equals(enclosingSymbol.OverriddenMethod, calledMethod);
        }
开发者ID:duncanpMS,项目名称:sonarlint-vs,代码行数:9,代码来源:OptionalParameterNotPassedToBaseCall.cs

示例12: CreateCompletionData

		protected virtual IEnumerable<CompletionData> CreateCompletionData (CompletionEngine engine, SemanticModel semanticModel, int position, ITypeSymbol returnType, Accessibility seenAccessibility, SyntaxToken startToken, SyntaxToken tokenBeforeReturnType, bool afterKeyword, CancellationToken cancellationToken)
		{
			var result = new List<CompletionData> ();
			ISet<ISymbol> overridableMembers;
			if (!TryDetermineOverridableMembers (semanticModel, tokenBeforeReturnType, seenAccessibility, out overridableMembers, cancellationToken)) {
				return result;
			}
			if (returnType != null) {
				overridableMembers = FilterOverrides (overridableMembers, returnType);
			}
			var curType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol> (position, cancellationToken);
			var declarationBegin = afterKeyword ? (startToken.Parent.AncestorsAndSelf ().OfType<IncompleteMemberSyntax> ().FirstOrDefault () ?? startToken.Parent).SpanStart : position - 1;
			foreach (var m in overridableMembers) {
				var data = engine.Factory.CreateNewOverrideCompletionData (this, declarationBegin, curType, m, afterKeyword);
				result.Add (data);
			}
			return result;
		}
开发者ID:sushihangover,项目名称:monodevelop,代码行数:18,代码来源:OverrideContextHandler.cs

示例13: ProcessExpressionChange

        private static void ProcessExpressionChange(ExpressionSyntax expression, SemanticModel semanticModel,
            ref ImmutableHashSet<IFieldSymbol> nonCandidateFields, ref ImmutableHashSet<IFieldSymbol> assignedAsReadonly)
        {
            var fieldSymbol = semanticModel.GetSymbolInfo(expression).Symbol as IFieldSymbol;
            if (fieldSymbol== null || !FieldIsRelevant(fieldSymbol))
            {
                return;
            }

            var constructorSymbol = semanticModel.GetEnclosingSymbol(expression.SpanStart) as IMethodSymbol;
            if (constructorSymbol == null)
            {
                nonCandidateFields = nonCandidateFields.Add(fieldSymbol);
                return;
            }

            if (constructorSymbol.MethodKind == MethodKind.Constructor &&
                constructorSymbol.ContainingType.Equals(fieldSymbol.ContainingType))
            {
                assignedAsReadonly = assignedAsReadonly.Add(fieldSymbol);
            }
            else
            {
                nonCandidateFields = nonCandidateFields.Add(fieldSymbol);
            }
        }
开发者ID:jango2015,项目名称:sonarlint-vs,代码行数:26,代码来源:FieldShouldBeReadonly.cs

示例14: AddDelegateHandlers


//.........这里部分代码省略.........
			CompletionData item;
			if (addDefault) {
				item = engine.Factory.CreateAnonymousMethod (
					this,
					"delegate",
					"Creates anonymous delegate.",
					"delegate {" + EolMarker + thisLineIndent,
					delegateEndString
				);
				if (!completionList.Any (i => i.DisplayText == item.DisplayText))
					completionList.Add (item);

				//if (LanguageVersion.Major >= 5)

				item = engine.Factory.CreateAnonymousMethod (
					this,
					"async delegate",
					"Creates anonymous async delegate.",
					"async delegate {" + EolMarker + thisLineIndent,
					delegateEndString
				);
				if (!completionList.Any (i => i.DisplayText == item.DisplayText))
					completionList.Add (item);
			}

			var sb = new StringBuilder ("(");
			var sbWithoutTypes = new StringBuilder ("(");
			for (int k = 0; k < delegateMethod.Parameters.Length; k++) {
				if (k > 0) {
					sb.Append (", ");
					sbWithoutTypes.Append (", ");
				}
				sb.Append (RoslynCompletionData.SafeMinimalDisplayString (delegateMethod.Parameters [k], semanticModel, position, overrideNameFormat));
				sbWithoutTypes.Append (delegateMethod.Parameters [k].Name);
			}

			sb.Append (")");
			sbWithoutTypes.Append (")");
			var signature = sb.ToString ()
				.Replace (", params ", ", ")
				.Replace ("(params ", "(");

			if (completionList.All (data => data.DisplayText != signature)) {
				item = engine.Factory.CreateAnonymousMethod (
					this,
					signature + " =>",
					"Creates typed lambda expression.",
					signature + " => ",
					(addSemicolon ? ";" : "")
				);
				if (!completionList.Any (i => i.DisplayText == item.DisplayText))
					completionList.Add (item);

				// if (LanguageVersion.Major >= 5) {

				item = engine.Factory.CreateAnonymousMethod (
					this,
					"async " + signature + " =>",
					"Creates typed async lambda expression.",
					"async " + signature + " => ",
					(addSemicolon ? ";" : "")
				);
				if (!completionList.Any (i => i.DisplayText == item.DisplayText))
					completionList.Add (item);

				var signatureWithoutTypes = sbWithoutTypes.ToString ();
				if (!delegateMethod.Parameters.Any (p => p.RefKind != RefKind.None) && completionList.All (data => data.DisplayText != signatureWithoutTypes)) {
					item = engine.Factory.CreateAnonymousMethod (
						this,
						signatureWithoutTypes + " =>",
						"Creates typed lambda expression.",
						signatureWithoutTypes + " => ",
						(addSemicolon ? ";" : "")
					);
					if (!completionList.Any (i => i.DisplayText == item.DisplayText))
						completionList.Add (item);

					//if (LanguageVersion.Major >= 5) {
					item = engine.Factory.CreateAnonymousMethod (
						this,
						"async " + signatureWithoutTypes + " =>",
						"Creates typed async lambda expression.",
						"async " + signatureWithoutTypes + " => ",
						(addSemicolon ? ";" : "")
					);
					if (!completionList.Any (i => i.DisplayText == item.DisplayText))
						completionList.Add (item);

					//}
				}
			}
			string varName = optDelegateName ?? "Handle" + delegateType.Name;

            
			var curType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol> (position, cancellationToken);
			var uniqueName = new UniqueNameGenerator (semanticModel).CreateUniqueMethodName (parent, varName);
			item = engine.Factory.CreateNewMethodDelegate (this, delegateType, uniqueName, curType);
			if (!completionList.Any (i => i.DisplayText == item.DisplayText))
				completionList.Add (item);
		}
开发者ID:zenek-y,项目名称:monodevelop,代码行数:101,代码来源:DelegateCreationContextHandler.cs

示例15: IsInsideConstructorDeclaration

 private static bool IsInsideConstructorDeclaration(ExpressionSyntax expression, INamedTypeSymbol currentType,
     SemanticModel semanticModel)
 {
     var constructorSymbol = semanticModel.GetEnclosingSymbol(expression.SpanStart) as IMethodSymbol;
     return constructorSymbol != null &&
         constructorSymbol.MethodKind == MethodKind.Constructor &&
         constructorSymbol.ContainingType.Equals(currentType);
 }
开发者ID:dbolkensteyn,项目名称:sonarlint-vs,代码行数:8,代码来源:GenericReadonlyFieldPropertyAssignment.cs


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