简体   繁体   English

Roslyn:获取第三方库中定义的类型的符号

[英]Roslyn: get the symbol for a type defined in a third-party library

using Roslyn/Microsoft.CodeAnalysis, how can I get the ISymbol for a third-party type, ie, a type defined in a referenced assembly which is not part of the solution?使用 Roslyn/Microsoft.CodeAnalysis,如何获取第三方类型的ISymbol ,即在不属于解决方案的引用程序集中定义的类型? 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.在我的特殊情况下,我正在寻找 JSON.NET 的 JObject,但实际上同样的问题对于 BCL 的东西(如 StringBuilder 等)也是有效的。

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.到目前为止,我提出的唯一想法是实现一个 CSharpSyntaxWalker,它查找所有方法调用、属性访问和构造函数调用,检查它们是否是在我感兴趣的类型上进行的,如果是,则从各自的 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.我认为必须有更好的方法,但是我的 google-fu 没有产生任何相关结果。

Maybe about the background: what I'm trying to do is replace the usage of JObject with the usage of another class.也许关于背景:我想要做的是用另一个类的用法替换 JObject 的用法。

If you can get access to a Compilation you can call Compilation.GetTypeByMetadataName() and pass in the fully qualified metadata name for the symbol.如果您可以访问Compilation ,则可以调用Compilation.GetTypeByMetadataName()并传入符号的完全限定元数据名称。

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?有关更多信息,请参阅: 类名中有“+”?

Once you have the symbol you can find all usages via SymbolFinder.FindAllReferences()获得符号后,您可以通过SymbolFinder.FindAllReferences()找到所有用法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM