我想使用Roslyn对以下类执行反射样式操作:
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);
}
}
基本上,我想获得符合我在上面反思示例中使用的标准的方法列表。此外,如果有人知道一个网站,解释如何做反射像操作与罗斯林,请随时指出我的方向。我一直在寻找几个小时,似乎无法在这方面取得进展。
提前致谢,
鲍勃
答案 0 :(得分:5)
获得所需的方法可以这样完成:
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;
}
你需要一个SyntaxTree。通过反射你正在使用程序集,所以我不知道你的问题的那部分的答案。如果你想将它作为Visual Studio的Roslyn扩展,那么这应该是你正在寻找的。 p>
答案 1 :(得分:0)
Bob,我建议您从随Roslyn CTP一起安装的语法和语义演练文档开始。它们表明大多数(如果不是全部的话)。