How to Perform Reflection Operations using Roslyn

江枫思渺然 提交于 2019-12-05 03:30:46

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/10713063/how-to-perform-reflection-operations-using-roslyn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!