问题描述
我想使用罗斯林下面的类进行反射式的操作:
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.
谢谢,
鲍勃
推荐答案
得到你想要可以这样做的方法:
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;
}
您将需要一个SyntaxTree。与反思你与装配工作,所以我不知道回答你的问题的一部分。如果你想这是一个罗斯林扩展Visual Studio中,那么这应该是你在找什么。
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.
这篇关于如何使用罗斯林执行操作的反思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!