Created
March 7, 2015 08:37
-
-
Save JoshVarty/14de33731724db22c8cb 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 = SyntaxFactory.ParseSyntaxTree(@" | |
using System; | |
namespace NS1 | |
{ | |
public class C | |
{ | |
int InstanceField = 0; | |
internal void InstanceMethod() | |
{ | |
Console.WriteLine(InstanceField); | |
} | |
} | |
} | |
namespace NS2 | |
{ | |
static class ExtensionMethods | |
{ | |
public static void ExtensionMethod(this NS1.C s) | |
{ | |
} | |
} | |
} | |
class Program | |
{ | |
static void Main() | |
{ | |
NS1.C c = new NS1.C(); | |
c.ToString(); | |
} | |
}"); | |
var compilation = CSharpCompilation.Create("MyCompilation", | |
syntaxTrees: new[] { tree }, references: new[] { MetadataReference.CreateFromAssembly(typeof(object).Assembly) }); | |
var results = new StringBuilder(); | |
// Traverse the symbol tree to find all namespaces, types, methods and fields. | |
// foreach (NamespaceSymbol ns in compilation.GetReferencedAssemblySymbol(mscorlib).GlobalNamespace.GetNamespaceMembers()) | |
foreach (var ns in compilation.Assembly.GlobalNamespace.GetNamespaceMembers()) | |
{ | |
results.AppendLine(); | |
results.Append(ns.Kind); | |
results.Append(": "); | |
results.Append(ns.Name); | |
foreach (var type in ns.GetTypeMembers()) | |
{ | |
results.AppendLine(); | |
results.Append(" "); | |
results.Append(type.TypeKind); | |
results.Append(": "); | |
results.Append(type.Name); | |
foreach (var member in type.GetMembers()) | |
{ | |
results.AppendLine(); | |
results.Append(" "); | |
if (member.Kind == SymbolKind.Field || member.Kind == SymbolKind.Method) | |
{ | |
results.Append(member.Kind); | |
results.Append(": "); | |
results.Append(member.Name); | |
} | |
} | |
} | |
} | |
Assert.AreEqual(@" | |
Namespace: NS1 | |
Class: C | |
Field: InstanceField | |
Method: InstanceMethod | |
Method: .ctor | |
Namespace: NS2 | |
Class: ExtensionMethods | |
Method: ExtensionMethod", results.ToString()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment