如何使用Roslyn执行reflection操作

我想使用Roslyn对以下类执行reflection样式操作:

public abstract class MyBaseClass { public bool Method1() { return true; } public bool Method2() { return true; } public void Method3() { } } 

基本上我想这样做,但与罗斯林:

 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); } } 

基本上,我想获得符合我在上面的reflection示例中使用的标准的方法列表。 此外,如果有人知道一个网站,解释如何使用Roslyn进行reflection操作,请随时指出我的方向。 我一直在寻找几个小时,似乎无法在这方面取得进展。

提前致谢,

短发

获得所需的方法可以这样做:

  public static IEnumerable 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(); 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; } 

你需要一个SyntaxTree。 通过reflection你正在使用程序集,所以我不知道你的问题的那部分的答案。 如果您希望将此作为Visual Studio的Roslyn扩展,那么这应该是您正在寻找的。

Bob,我建议您从随Roslyn CTP一起安装的语法和语义演练文档开始。 它们表明大多数(如果不是全部)。