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


C# SemanticModel.GetTypeInfo方法代码示例

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


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

示例1: DetermineParameterType

        public static ITypeSymbol DetermineParameterType(
            this ArgumentSyntax argument,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            TypeInfo typeInfo;

            if (argument.Expression.Kind() == SyntaxKind.DeclarationExpression)
            {
                var decl = (DeclarationExpressionSyntax)argument.Expression;
                var component = decl.VariableComponent as TypedVariableComponentSyntax;
                if (component == null) return semanticModel.Compilation.ObjectType;
                typeInfo = semanticModel.GetTypeInfo(component.Type);
                return typeInfo.Type?.IsErrorType() == false ? typeInfo.Type : semanticModel.Compilation.ObjectType;
            }

            // If a parameter appears to have a void return type, then just use 'object'
            // instead.
            typeInfo = semanticModel.GetTypeInfo(argument.Expression, cancellationToken);
            if (typeInfo.Type != null && typeInfo.Type.SpecialType == SpecialType.System_Void)
            {
                return semanticModel.Compilation.ObjectType;
            }

            return semanticModel.GetType(argument.Expression, cancellationToken);
        }
开发者ID:jkotas,项目名称:roslyn,代码行数:26,代码来源:InternalExtensions.cs

示例2: GetOuterCastType

        private static ITypeSymbol GetOuterCastType(ExpressionSyntax expression, SemanticModel semanticModel, out bool parentIsOrAsExpression)
        {
            expression = expression.WalkUpParentheses();
            parentIsOrAsExpression = false;

            var parentNode = expression.Parent;
            if (parentNode == null)
            {
                return null;
            }

            if (parentNode.IsKind(SyntaxKind.CastExpression))
            {
                var castExpression = (CastExpressionSyntax)parentNode;
                return semanticModel.GetTypeInfo(castExpression).Type;
            }

            if (parentNode.IsKind(SyntaxKind.IsExpression) ||
                parentNode.IsKind(SyntaxKind.AsExpression))
            {
                parentIsOrAsExpression = true;
                return null;
            }

            if (parentNode.IsKind(SyntaxKind.ArrayRankSpecifier))
            {
                return semanticModel.Compilation.GetSpecialType(SpecialType.System_Int32);
            }

            if (parentNode.IsKind(SyntaxKind.SimpleMemberAccessExpression))
            {
                var memberAccess = (MemberAccessExpressionSyntax)parentNode;
                if (memberAccess.Expression == expression)
                {
                    var memberSymbol = semanticModel.GetSymbolInfo(memberAccess).Symbol;
                    if (memberSymbol != null)
                    {
                        return memberSymbol.ContainingType;
                    }
                }
            }

            if (parentNode.IsKind(SyntaxKind.ConditionalExpression) &&
                ((ConditionalExpressionSyntax)parentNode).Condition == expression)
            {
                return semanticModel.Compilation.GetSpecialType(SpecialType.System_Boolean);
            }

            if ((parentNode is PrefixUnaryExpressionSyntax || parentNode is PostfixUnaryExpressionSyntax) &&
                !semanticModel.GetConversion(expression).IsUserDefined)
            {
                var parentEpression = (ExpressionSyntax)parentNode;
                return GetOuterCastType(parentEpression, semanticModel, out parentIsOrAsExpression) ?? semanticModel.GetTypeInfo(parentEpression).ConvertedType;
            }

            return null;
        }
开发者ID:riversky,项目名称:roslyn,代码行数:57,代码来源:CastExpressionSyntaxExtensions.cs

示例3: AnalyzeBinaryExpression

 private static void AnalyzeBinaryExpression(BinaryExpressionSyntax node, SemanticModel model, Action<Diagnostic> addDiagnostic)
 {
     var leftType = model.GetTypeInfo(node.Left).Type;
     var rightType = model.GetTypeInfo(node.Right).Type;
     if (leftType != null && rightType != null && leftType.SpecialType == SpecialType.System_String && rightType.SpecialType == SpecialType.System_String)
     {
         addDiagnostic(node.OperatorToken.GetLocation().CreateDiagnostic(Rule));
     }
 }
开发者ID:elemk0vv,项目名称:roslyn-1,代码行数:9,代码来源:CSharpCA1309DiagnosticAnalyzer.cs

示例4: TryInitializeState

        protected override bool TryInitializeState(
            Document document, SemanticModel model, SyntaxNode node, CancellationToken cancellationToken,
            out INamedTypeSymbol classType, out INamedTypeSymbol abstractClassType)
        {
            var baseClassNode = node as TypeSyntax;
            if (baseClassNode != null && baseClassNode.Parent is BaseTypeSyntax &&
                baseClassNode.Parent.IsParentKind(SyntaxKind.BaseList) &&
                ((BaseTypeSyntax)baseClassNode.Parent).Type == baseClassNode)
            {
                if (baseClassNode.Parent.Parent.IsParentKind(SyntaxKind.ClassDeclaration))
                {
                    abstractClassType = model.GetTypeInfo(baseClassNode, cancellationToken).Type as INamedTypeSymbol;
                    cancellationToken.ThrowIfCancellationRequested();

                    if (abstractClassType.IsAbstractClass())
                    {
                        var classDecl = baseClassNode.Parent.Parent.Parent as ClassDeclarationSyntax;
                        classType = model.GetDeclaredSymbol(classDecl, cancellationToken) as INamedTypeSymbol;

                        return classType != null && abstractClassType != null;
                    }
                }
            }

            classType = null;
            abstractClassType = null;
            return false;
        }
开发者ID:RoryVL,项目名称:roslyn,代码行数:28,代码来源:CSharpImplementAbstractClassService.cs

示例5: IsTypeInferred

        /// <summary>
        /// Determines whether the specified TypeSyntax is actually 'var'.
        /// </summary>
        public static bool IsTypeInferred(this TypeSyntax typeSyntax, SemanticModel semanticModel)
        {
            if (!typeSyntax.IsVar)
            {
                return false;
            }

            if (semanticModel.GetAliasInfo(typeSyntax) != null)
            {
                return false;
            }

            var type = semanticModel.GetTypeInfo(typeSyntax).Type;
            if (type == null)
            {
                return false;
            }

            if (type.Name == "var")
            {
                return false;
            }

            return true;
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:28,代码来源:TypeSyntaxExtensions.cs

示例6: IsTypeApparentInDeclaration

 /// <summary>
 /// Returns true if type information could be gleaned by simply looking at the given statement.
 /// This typically means that the type name occurs in right hand side of an assignment.
 /// </summary>
 private bool IsTypeApparentInDeclaration(VariableDeclarationSyntax variableDeclaration, SemanticModel semanticModel, TypeStylePreference stylePreferences, CancellationToken cancellationToken)
 {
     var initializer = variableDeclaration.Variables.Single().Initializer;
     var initializerExpression = GetInitializerExpression(initializer);
     var declaredTypeSymbol = semanticModel.GetTypeInfo(variableDeclaration.Type, cancellationToken).Type;
     return TypeStyleHelper.IsTypeApparentInAssignmentExpression(stylePreferences, initializerExpression, semanticModel,cancellationToken, declaredTypeSymbol);
 }
开发者ID:jkotas,项目名称:roslyn,代码行数:11,代码来源:CSharpTypeStyleDiagnosticAnalyzerBase.State.cs

示例7: GetDiagnosticsForNode

 protected void GetDiagnosticsForNode(SyntaxNode node, SemanticModel model, Action<Diagnostic> addDiagnostic)
 {
     var type = model.GetTypeInfo(node).Type;
     if (type != null && TypeHasWeakIdentity(type, model))
     {
         addDiagnostic(node.CreateDiagnostic(Rule, type.ToDisplayString()));
     }
 }
开发者ID:modulexcite,项目名称:pattern-matching-csharp,代码行数:8,代码来源:CA2002DiagnosticAnalyzer.cs

示例8: TryGetExpressionType

 protected static bool TryGetExpressionType(
     SyntaxNode expression,
     SemanticModel semanticModel,
     out INamedTypeSymbol returnType)
 {
     var typeInfo = semanticModel.GetTypeInfo(expression);
     returnType = typeInfo.Type as INamedTypeSymbol;
     return returnType != null;
 }
开发者ID:XieShuquan,项目名称:roslyn,代码行数:9,代码来源:AbstractAddAwaitCodeFixProvider.cs

示例9: GetMethodGroupItems

        private IEnumerable<SignatureHelpItem> GetMethodGroupItems(
            InvocationExpressionSyntax invocationExpression,
            SemanticModel semanticModel,
            ISymbolDisplayService symbolDisplayService,
            IAnonymousTypeDisplayService anonymousTypeDisplayService,
            IDocumentationCommentFormattingService documentationCommentFormattingService,
            ISymbol within,
            IEnumerable<IMethodSymbol> methodGroup,
            CancellationToken cancellationToken)
        {
            ITypeSymbol throughType = null;
            if (invocationExpression.Expression is MemberAccessExpressionSyntax)
            {
                var throughExpression = ((MemberAccessExpressionSyntax)invocationExpression.Expression).Expression;
                var throughSymbol = semanticModel.GetSymbolInfo(throughExpression, cancellationToken).GetAnySymbol();

                // if it is via a base expression "base.", we know the "throughType" is the base class but
                // we need to be able to tell between "base.M()" and "new Base().M()".
                // currently, Access check methods do not differentiate between them.
                // so handle "base." primary-expression here by nulling out "throughType"
                if (!(throughExpression is BaseExpressionSyntax))
                {
                    throughType = semanticModel.GetTypeInfo(throughExpression, cancellationToken).Type;
                }

                var includeInstance = !throughExpression.IsKind(SyntaxKind.IdentifierName) ||
                    semanticModel.LookupSymbols(throughExpression.SpanStart, name: throughSymbol.Name).Any(s => !(s is INamedTypeSymbol)) ||
                    (!(throughSymbol is INamespaceOrTypeSymbol) && semanticModel.LookupSymbols(throughExpression.SpanStart, container: throughSymbol.ContainingType).Any(s => !(s is INamedTypeSymbol)));

                var includeStatic = throughSymbol is INamedTypeSymbol ||
                    (throughExpression.IsKind(SyntaxKind.IdentifierName) &&
                    semanticModel.LookupNamespacesAndTypes(throughExpression.SpanStart, name: throughSymbol.Name).Any(t => t.GetSymbolType() == throughType));

                Contract.ThrowIfFalse(includeInstance || includeStatic);
                methodGroup = methodGroup.Where(m => (m.IsStatic && includeStatic) || (!m.IsStatic && includeInstance));
            }
            else if (invocationExpression.Expression is SimpleNameSyntax &&
                invocationExpression.IsInStaticContext())
            {
                methodGroup = methodGroup.Where(m => m.IsStatic);
            }

            var accessibleMethods = methodGroup.Where(m => m.IsAccessibleWithin(within, throughTypeOpt: throughType)).ToList();
            if (accessibleMethods.Count == 0)
            {
                return null;
            }

            var methodSet = accessibleMethods.ToSet();
            accessibleMethods = accessibleMethods.Where(m => !IsHiddenByOtherMethod(m, methodSet)).ToList();

            return accessibleMethods.Select(m =>
                ConvertMethodGroupMethod(m, invocationExpression, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, cancellationToken));
        }
开发者ID:CAPCHIK,项目名称:roslyn,代码行数:54,代码来源:InvocationExpressionSignatureHelpProvider_MethodGroup.cs

示例10: TryDetermineReturnType

        public override bool TryDetermineReturnType(SyntaxToken startToken, SemanticModel semanticModel, CancellationToken cancellationToken, out ITypeSymbol returnType, out SyntaxToken nextToken)
        {
            nextToken = startToken;
            returnType = null;
            if (startToken.Parent is TypeSyntax)
            {
                var typeSyntax = (TypeSyntax)startToken.Parent;

                // 'partial' is actually an identifier.  If we see it just bail.  This does mean
                // we won't handle overrides that actually return a type called 'partial'.  And
                // not a single tear was shed.
                if (typeSyntax is IdentifierNameSyntax &&
                    ((IdentifierNameSyntax)typeSyntax).Identifier.IsKindOrHasMatchingText(SyntaxKind.PartialKeyword))
                {
                    return false;
                }

                returnType = semanticModel.GetTypeInfo(typeSyntax, cancellationToken).Type;
                nextToken = typeSyntax.GetFirstToken().GetPreviousToken();
            }

            return true;
        }
开发者ID:Rickinio,项目名称:roslyn,代码行数:23,代码来源:OverrideCompletionProvider.cs

示例11: ClassifyUsingDirectiveSyntax

        private IEnumerable<ClassifiedSpan> ClassifyUsingDirectiveSyntax(
            UsingDirectiveSyntax usingDirective,
            SemanticModel semanticModel,
            CancellationToken cancellationToken)
        {
            // For using aliases, we bind the target on the right of the equals and use that
            // binding to classify the alias.
            if (usingDirective.Alias != null)
            {
                var info = semanticModel.GetTypeInfo(usingDirective.Name, cancellationToken);
                if (info.Type != null)
                {
                    var classification = GetClassificationForType(info.Type);
                    if (classification != null)
                    {
                        var token = usingDirective.Alias.Name;
                        return SpecializedCollections.SingletonEnumerable(new ClassifiedSpan(token.Span, classification));
                    }
                }
            }

            return null;
        }
开发者ID:EkardNT,项目名称:Roslyn,代码行数:23,代码来源:UsingDirectiveSyntaxClassifier.cs

示例12: VerifySpeculativeSemanticModelForMethodBody

        private static void VerifySpeculativeSemanticModelForMethodBody(BlockSyntax blockStatement, SemanticModel speculativeModel)
        {
            var localDecl = (LocalDeclarationStatementSyntax)blockStatement.Statements[0];
            var declarator = localDecl.Declaration.Variables.First();
            var local = speculativeModel.GetDeclaredSymbol(declarator);
            Assert.NotNull(local);
            Assert.Equal("z", local.Name);
            Assert.Equal(SymbolKind.Local, local.Kind);
            Assert.Equal("Int32", ((LocalSymbol)local).Type.Name);

            var typeInfo = speculativeModel.GetTypeInfo(localDecl.Declaration.Type);
            Assert.NotNull(typeInfo.Type);
            Assert.Equal("Int32", typeInfo.Type.Name);

            var call = (InvocationExpressionSyntax)((ExpressionStatementSyntax)blockStatement.Statements[1]).Expression;
            var arg = call.ArgumentList.Arguments[0].Expression;
            var info = speculativeModel.GetSymbolInfo(arg);
            Assert.NotNull(info.Symbol);
            Assert.Equal("z", info.Symbol.Name);
            Assert.Equal(SymbolKind.Local, info.Symbol.Kind);

            // Shouldn't bind to local y in the original method as we are replacing the method body.
            var call2 = (InvocationExpressionSyntax)((ExpressionStatementSyntax)((BlockSyntax)blockStatement).Statements[2]).Expression;
            var arg2 = call2.ArgumentList.Arguments[0].Expression;
            var info2 = speculativeModel.GetSymbolInfo(arg2);
            Assert.Null(info2.Symbol);
        }
开发者ID:riversky,项目名称:roslyn,代码行数:27,代码来源:SemanticModelAPITests.cs

示例13: VerifyModelForOutVar

        private static void VerifyModelForOutVar(
            SemanticModel model,
            DeclarationExpressionSyntax decl,
            bool isDelegateCreation,
            bool isExecutableCode,
            bool isShadowed,
            bool verifyDataFlow = true,
            params IdentifierNameSyntax[] references)
        {
            var variableDeclaratorSyntax = GetVariableDesignation(decl);
            var symbol = model.GetDeclaredSymbol(variableDeclaratorSyntax);
            Assert.NotNull(symbol);
            Assert.Equal(decl.Identifier().ValueText, symbol.Name);
            Assert.Equal(variableDeclaratorSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
            Assert.Equal(LocalDeclarationKind.RegularVariable, ((LocalSymbol)symbol).DeclarationKind);
            Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDeclaratorSyntax));

            if (isShadowed)
            {
                Assert.NotEqual(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single());
            }
            else
            {
                Assert.Same(symbol, model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText).Single());
            }

            Assert.True(model.LookupNames(decl.SpanStart).Contains(decl.Identifier().ValueText));

            var local = (SourceLocalSymbol)symbol;
            var typeSyntax = decl.Type();

            Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(typeSyntax));
            Assert.True(SyntaxFacts.IsInTypeOnlyContext(typeSyntax));

            if (typeSyntax.IsVar && local.IsVar && local.Type.IsErrorType())
            {
                Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol);
            }
            else
            {
                Assert.Equal(local.Type, model.GetSymbolInfo(typeSyntax).Symbol);
            }

            Assert.Same(symbol, model.GetSymbolInfo(decl).Symbol);
            Assert.Equal(local.Type, model.GetTypeInfo(decl).Type);
            Assert.Null(model.GetDeclaredSymbol(decl));

            foreach (var reference in references)
            {
                Assert.Same(symbol, model.GetSymbolInfo(reference).Symbol);
                Assert.Same(symbol, model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText).Single());
                Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText));
                Assert.Equal(local.Type, model.GetTypeInfo(reference).Type);
            }

            if (verifyDataFlow)
            {
                VerifyDataFlow(model, decl, isDelegateCreation, isExecutableCode, references, symbol);
            }
        }
开发者ID:orthoxerox,项目名称:roslyn,代码行数:60,代码来源:OutVarTests.cs

示例14: VerifyModelNotSupported

 private static void VerifyModelNotSupported(SemanticModel model, params IdentifierNameSyntax[] references)
 {
     foreach (var reference in references)
     {
         Assert.Null(model.GetSymbolInfo(reference).Symbol);
         Assert.False(model.LookupSymbols(reference.SpanStart, name: reference.Identifier.ValueText).Any());
         Assert.DoesNotContain(reference.Identifier.ValueText, model.LookupNames(reference.SpanStart));
         Assert.True(((TypeSymbol)model.GetTypeInfo(reference).Type).IsErrorType());
     }
 }
开发者ID:orthoxerox,项目名称:roslyn,代码行数:10,代码来源:OutVarTests.cs

示例15: VerifyModelForOutField

        private static void VerifyModelForOutField(
            SemanticModel model,
            DeclarationExpressionSyntax decl,
            bool duplicate,
            params IdentifierNameSyntax[] references)
        {
            var variableDesignationSyntax = GetVariableDesignation(decl);
            var symbol = model.GetDeclaredSymbol(variableDesignationSyntax);
            Assert.Equal(decl.Identifier().ValueText, symbol.Name);
            Assert.Equal(SymbolKind.Field, symbol.Kind);
            Assert.Equal(variableDesignationSyntax, symbol.DeclaringSyntaxReferences.Single().GetSyntax());
            Assert.Same(symbol, model.GetDeclaredSymbol((SyntaxNode)variableDesignationSyntax));

            var symbols = model.LookupSymbols(decl.SpanStart, name: decl.Identifier().ValueText);
            var names = model.LookupNames(decl.SpanStart);

            if (duplicate)
            {
                Assert.True(symbols.Count() > 1);
                Assert.Contains(symbol, symbols);
            }
            else
            {
                Assert.Same(symbol, symbols.Single());
            }

            Assert.Contains(decl.Identifier().ValueText, names);

            var local = (FieldSymbol)symbol;
            var typeSyntax = decl.Type();

            Assert.True(SyntaxFacts.IsInNamespaceOrTypeContext(typeSyntax));
            Assert.True(SyntaxFacts.IsInTypeOnlyContext(typeSyntax));

            if (typeSyntax.IsVar && local.Type.IsErrorType())
            {
                Assert.Null(model.GetSymbolInfo(typeSyntax).Symbol);
            }
            else
            {
                Assert.Equal(local.Type, model.GetSymbolInfo(typeSyntax).Symbol);
            }

            var declarator = decl.Ancestors().OfType<VariableDeclaratorSyntax>().FirstOrDefault();
            var inFieldDeclaratorArgumentlist = declarator != null && declarator.Parent.Parent.Kind() != SyntaxKind.LocalDeclarationStatement &&
                                           (declarator.ArgumentList?.Contains(decl)).GetValueOrDefault();
            if (inFieldDeclaratorArgumentlist)
            {
                Assert.Null(model.GetSymbolInfo(decl).Symbol);
                Assert.Null(model.GetSymbolInfo(decl).Symbol);
            }
            else
            {
                Assert.Same(symbol, model.GetSymbolInfo(decl).Symbol);
                Assert.Same(symbol, model.GetSymbolInfo(decl).Symbol);
            }

            Assert.Null(model.GetDeclaredSymbol(decl));

            foreach (var reference in references)
            {
                var referenceInfo = model.GetSymbolInfo(reference);
                symbols = model.LookupSymbols(reference.SpanStart, name: decl.Identifier().ValueText);

                if (duplicate)
                {
                    Assert.Null(referenceInfo.Symbol);
                    Assert.Contains(symbol, referenceInfo.CandidateSymbols);
                    Assert.True(symbols.Count() > 1);
                    Assert.Contains(symbol, symbols);
                }
                else
                {
                    Assert.Same(symbol, referenceInfo.Symbol);
                    Assert.Same(symbol, symbols.Single());
                    Assert.Equal(local.Type, model.GetTypeInfo(reference).Type);
                }

                Assert.True(model.LookupNames(reference.SpanStart).Contains(decl.Identifier().ValueText));
            }

            if (!inFieldDeclaratorArgumentlist)
            {
                var dataFlowParent = (ExpressionSyntax)decl.Parent.Parent.Parent;

                if (model.IsSpeculativeSemanticModel)
                {
                    Assert.Throws<NotSupportedException>(() => model.AnalyzeDataFlow(dataFlowParent));
                }
                else
                {
                    var dataFlow = model.AnalyzeDataFlow(dataFlowParent);

                    if (dataFlow.Succeeded)
                    {
                        Assert.False(dataFlow.VariablesDeclared.Contains(symbol, ReferenceEqualityComparer.Instance));
                        Assert.False(dataFlow.AlwaysAssigned.Contains(symbol, ReferenceEqualityComparer.Instance));
                        Assert.False(dataFlow.WrittenInside.Contains(symbol, ReferenceEqualityComparer.Instance));
                        Assert.False(dataFlow.DataFlowsIn.Contains(symbol, ReferenceEqualityComparer.Instance));
                        Assert.False(dataFlow.ReadInside.Contains(symbol, ReferenceEqualityComparer.Instance));
//.........这里部分代码省略.........
开发者ID:orthoxerox,项目名称:roslyn,代码行数:101,代码来源:OutVarTests.cs


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