Roslyn:获取第三方库中定义的类型的符号 [英] Roslyn: get the symbol for a type defined in a third-party library

查看:36
本文介绍了Roslyn:获取第三方库中定义的类型的符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 Roslyn/Microsoft.CodeAnalysis,我怎样才能获得第三方类型的 ISymbol,即在引用程序集中定义的类型,它不是解决方案的一部分?在我的特定情况下,我正在寻找 JSON.NET 的 JObject,但实际上同样的问题对 BCL 的东西(如 StringBuilder 等)有效.

using Roslyn/Microsoft.CodeAnalysis, how can I get the ISymbolfor a third-party type, ie, a type defined in a referenced assembly which is not part of the solution? In my particular case, I'm looking for JSON.NET's JObject, but actually the same question would be valid for BCL stuff like StringBuilder etc.

到目前为止我提出的唯一想法是实现一个 CSharpSyntaxWalker,它查找所有方法调用、属性访问和构造函数调用,检查它们是否是在我感兴趣的类型上进行的,如果是,则获取来自相应 SyntaxNode 的符号.我现在要实现这个,但它看起来非常麻烦.我认为一定有更好的方法,但我的 google-fu 没有产生任何相关结果.

The only idea I've come up so far is to implement a CSharpSyntaxWalker which looks for all method invocations, property accesses and constructor calls, checks whether they are made on the type I'm interested in and if yes, gets the symbol from the respective SyntaxNode. I'm going to implement this now, but it seems awfully cumbersome. I think there must a better way, but my google-fu has not yielded any relevant results.

也许是关于背景:我想要做的是用另一个类的用法替换 JObject 的用法.

Maybe about the background: what I'm trying to do is replace the usage of JObject with the usage of another class.

推荐答案

如果您可以访问 Compilation,您可以致电 Compilation.GetTypeByMetadataName() 并传入符号的完全限定元数据名称.

If you can get access to a Compilation you can call Compilation.GetTypeByMetadataName() and pass in the fully qualified metadata name for the symbol.

请注意嵌套类和泛型,它们的元数据名称与正常的完全限定名称不同.有关更多信息,请参阅:拥有+"在类名中?

Be careful of nested classes and generics, their metadata names are different than they're normal fully qualified names. For more see: Having a "+" in the class name?

获得符号后,您可以通过 <代码>SymbolFinder.FindAllReferences()

Once you have the symbol you can find all usages via SymbolFinder.FindAllReferences()

这篇关于Roslyn:获取第三方库中定义的类型的符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆