Last active
December 9, 2018 06:10
-
-
Save JoshVarty/fafdbe2d9e287898bbef to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var tree = CSharpSyntaxTree.ParseText(@" | |
public class MyClass { | |
int Method1() { return 0; } | |
void Method2() | |
{ | |
int x = Method1(); | |
} | |
} | |
}"); | |
var Mscorlib = PortableExecutableReference.CreateFromAssembly(typeof(object).Assembly); | |
var compilation = CSharpCompilation.Create("MyCompilation", | |
syntaxTrees: new[] { tree }, references: new[] { Mscorlib }); | |
var model = compilation.GetSemanticModel(tree); | |
//Looking at the first method symbol | |
var methodSyntax = tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().First(); | |
var methodSymbol = model.GetDeclaredSymbol(methodSyntax); | |
Console.WriteLine(methodSymbol.ToString()); //MyClass.Method1() | |
Console.WriteLine(methodSymbol.ContainingSymbol); //MyClass | |
Console.WriteLine(methodSymbol.IsAbstract); //false | |
//Looking at the first invocation | |
var invocationSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); | |
var invokedSymbol = model.GetSymbolInfo(invocationSyntax).Symbol; //Same as MyClass.Method1 | |
Console.WriteLine(invokedSymbol.ToString()); //MyClass.Method1() | |
Console.WriteLine(invokedSymbol.ContainingSymbol); //MyClass | |
Console.WriteLine(invokedSymbol.IsAbstract); //false | |
Console.WriteLine(invokedSymbol.Equals(methodSymbol)); //true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment