Reputation: 2894
I would like to perform reflection style operations on the following class using Roslyn:
public abstract class MyBaseClass
{
public bool Method1()
{
return true;
}
public bool Method2()
{
return true;
}
public void Method3()
{
}
}
Basically I want to do this, but with Roslyn:
BindingFlags flags = BindingFlags.Public |
BindingFlags.Instance;
MethodInfo[] mBaseClassMethods = typeof(MyBaseClass).GetMethods(flags);
foreach (MethodInfo mi in mBaseClassMethods)
{
if (mi.GetParameters().Length == 0 && mi.ReturnType == typeof(void))
{
methodInfos.Add(mi);
}
if (mi.GetParameters().Length == 0 && mi.ReturnType == typeof(bool))
{
methodInfos.Add(mi);
}
}
Essentially, I would like to get a list of the methods that meet the criteria I used in the reflection example above. Also, if anyone knows of a site that explains how to do Reflection like operations with Roslyn please feel free to point me in that direction. I've been searching for hours and can't seem to make progress on this.
Thanks in advance,
Bob
Upvotes: 5
Views: 2128
Reputation: 316
Getting the methods you want can be done like this:
public static IEnumerable<MethodDeclarationSyntax> BobsFilter(SyntaxTree tree)
{
var compilation = Compilation.Create("test", syntaxTrees: new[] { tree });
var model = compilation.GetSemanticModel(tree);
var types = new[] { SpecialType.System_Boolean, SpecialType.System_Void };
var methods = tree.Root.DescendentNodes().OfType<MethodDeclarationSyntax>();
var publicInternalMethods = methods.Where(m => m.Modifiers.Any(t => t.Kind == SyntaxKind.PublicKeyword || t.Kind == SyntaxKind.InternalKeyword));
var withoutParameters = publicInternalMethods.Where(m => !m.ParameterList.Parameters.Any());
var withReturnBoolOrVoid = withoutParameters.Where(m => types.Contains(model.GetSemanticInfo(m.ReturnType).ConvertedType.SpecialType));
return withReturnBoolOrVoid;
}
You'll need a SyntaxTree for that. With reflection you're working with assemblies, so I don't know the answer to that part of your question. If you want this as a Roslyn extension for Visual Studio, then this should be what you're looking for.
Upvotes: 8
Reputation: 11615
Bob, I suggest that you start with the Syntax and Semantic walkthrough documents that are installed with the Roslyn CTP. They indicate most if not all of this.
Upvotes: 0