//[TestCase("Method()")] public void TryGetWalked(string expression) { var code = @" namespace RoslynSandbox { class C { public readonly int field = typeof(int); public C() { var local = typeof(int); _ = local.ToString(); } public Type CalculatedProperty => typeof(int); public Type GetOnlyProperty { get; } = typeof(int); public static Type Method() => typeof(int); } }".AssertReplace("local.ToString()", $"{expression}.ToString()"); var syntaxTree = CSharpSyntaxTree.ParseText(code); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes()); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = ((MemberAccessExpressionSyntax)syntaxTree.FindInvocation("ToString()").Expression).Expression; var context = new SyntaxNodeAnalysisContext(null, null, semanticModel, null, null, null, CancellationToken.None); Assert.AreEqual(true, Type.TryGet(node, context, out var type, out var source)); Assert.AreEqual("int", type.ToDisplayString()); Assert.AreEqual("typeof(int)", source.ToString()); }
public void TryGetAssemblyLoad(string expression) { var code = @" namespace RoslynSandbox { using System; using System.Collections.Generic; using System.Reflection; class C { public readonly int Field; public C(C foo) { var type = Assembly.Load(""mscorlib"").GetType(""System.Int32""); } public int Property { get; } public class Baz<T> { } public class Nested { } } }".AssertReplace("Assembly.Load(\"mscorlib\").GetType(\"System.Int32\")", expression); var syntaxTree = CSharpSyntaxTree.ParseText(code); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes()); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindExpression(expression); var context = new SyntaxNodeAnalysisContext(null, null, semanticModel, null, null, null, CancellationToken.None); Assert.AreEqual(false, Type.TryGet(node, context, out _, out _)); }
public void TryGet(string expression, string expected, string expectedSource) { var code = @" namespace RoslynSandbox { using System; using System.Collections.Generic; using System.Reflection; class C { public readonly int Field; public C(C foo, int? nullableInt) { var type = typeof(C); } public int Property { get; } public class Baz<T> { } public class Nested { } } }".AssertReplace("typeof(C)", expression); var syntaxTree = CSharpSyntaxTree.ParseText(code); var compilation = CSharpCompilation.Create("test", new[] { syntaxTree }, MetadataReferences.FromAttributes()); var semanticModel = compilation.GetSemanticModel(syntaxTree); var node = syntaxTree.FindExpression(expression); var context = new SyntaxNodeAnalysisContext(null, null, semanticModel, null, null, null, CancellationToken.None); Assert.AreEqual(true, Type.TryGet(node, context, out var type, out var source)); Assert.AreEqual(expected, type.ToDisplayString()); Assert.AreEqual(expectedSource, source.ToString()); }