SemanticModel..GetSymbolInfo / GetDeclaredSymbol返回null

时间:2019-06-15 08:11:45

标签: c# roslyn

我试图获取方法调用的符号,但我总是得到空值。

我检查了对System.Data的所有引用,并在文件中使用了System.Data

connection.Open();的代码:

case SyntaxKind.InvocationExpression:

 var ourMethodName = ((MemberAccessExpressionSyntax)((InvocationExpressionSyntax)expression).Expression).Name;
                        var invocation = expression as InvocationExpressionSyntax;
                        var methodSymbol = (IMethodSymbol)model.GetSymbolInfo(invocation).Symbol;

测试:


 public void TestDereferenceOnKnownNull()
        {
            var code = @"using System.Data.SqlClient;using System.IO;" +
            @"
            public class C
            {


                public SqlConnection connection = new SqlConnection("" "");

              public void M()
              {
                connection.Open();

                }       
            }
            ";

            var dx = GetAnalyzerDiagnostics(code);
            Assert.AreEqual(1, dx.Length);
            Assert.AreEqual(DBAnalyzer.PossibleEndOfScopeWithoutCloseId, dx[0].Id);
        }

 protected Diagnostic[] GetAnalyzerDiagnostics(string code)
        {
            code = code + @"";
            var document = CreateDocument(code, LanguageNames.CSharp);
            var analyzer = new DBAnalyzer();

            var compilerDiagnostics = document.Project.AddMetadataReference(MetadataReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8\System.Data.dll"));
            var  compilerDiagnostics2 = compilerDiagnostics.AddMetadataReference(MetadataReference.CreateFromFile(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.8\System.dll")).GetCompilationAsync().Result.GetDiagnostics();
            bool hasCompileErrors = compilerDiagnostics2.Any(d => d.Severity == DiagnosticSeverity.Error);
            Assert.AreEqual(hasCompileErrors, false, "Compilation error(s)");

            return GetSortedDiagnosticsFromDocuments(analyzer, new[] { document });
        }


我希望获得SqlConnection作为符号,但我得到Null。

0 个答案:

没有答案