我需要使用Roslyn获取有关方法调用到DLL的信息。例如,我有以下方法,其中dllObject是DLL文件的一部分。
public void MyMethod()
{
dllObject.GetMethod();
}
是否可以提取GetMethod的方法信息,例如它的名称,类名和程序集名称。
是的,您需要首先在语法树中搜索InvocationExpressionSyntax
,然后使用SemanticModel
检索它的完整符号,该符号应包含有关其全名(.ToString()
),类(.ContainingType
)和程序集(.ContainingAssembly
)的信息。
以下示例是自包含的,因此它不使用外部DLL,但相同的方法应适用于外部类型。
var tree = CSharpSyntaxTree.ParseText(@"
public class MyClass {
int Method1() { return 0; }
void Method2()
{
int x = Method1();
}
}
}");
var Mscorlib = PortableExecutableReference.CreateFromAssembly(typeof(object).Assembly);
var compilation = CSharpCompilation.Create("MyCompilation",
syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
var model = compilation.GetSemanticModel(tree);
//Looking at the first invocation
var invocationSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First();
var invokedSymbol = model.GetSymbolInfo(invocationSyntax).Symbol; //Same as MyClass.Method1
//Get name
var name = invokedSymbol.ToString();
//Get class
var parentClass = invokedSymbol.ContainingType;
//Get assembly
var assembly = invokedSymbol.ContainingAssembly;
几年前我写了一篇关于Semantic Model
的简短博文,你可能会觉得有帮助。