[英]How to browse an assembly's content without source code in Roslyn
Roslyn allows you to get the CSharpCompilation
from the source code: Roslyn允许您从源代码中获取
CSharpCompilation
:
// Getting the AST node
var tree = (CSharpSyntaxTree)CSharpSyntaxTree.ParseText("my code");
// Loading the semantic model
CSharpCompilation compilation = CSharpCompilation.Create("Compilation", new[] { tree });
Then I get the SemanticModel
: 然后我得到
SemanticModel
:
var sm = compilation.GetSemanticModel(tree);
The I usually try to get symbols like this: 我通常会尝试这样的符号:
sm.GetSymbolInfo(node);
What if I have no source code? 如果我没有源代码怎么办?
CSharpCompilation
without having the source code but just the DLL? CSharpCompilation
? Is Roslyn capable of this? 罗斯林能胜任吗?
Roslyn is not meant for reading assemblies, reflection libraries like System.Reflection, Mono.Cecil, System.Reflection.Metadata or IKVM.Reflection are likely going to be better suited for that. Roslyn不是用于读取程序集,反射库如System.Reflection,Mono.Cecil,System.Reflection.Metadata或IKVM.Reflection可能更适合它。
That being said, if you really want to do it, you can get a symbol for an assembly by creating a dummy compilation that references the assembly and then using GetAssemblyOrModuleSymbol
. 话虽这么说,如果你真的想这样做,你可以通过创建引用程序集然后使用
GetAssemblyOrModuleSymbol
的虚拟编译来获得程序集的GetAssemblyOrModuleSymbol
。 For example, to write all types in an assembly to the console, you can use code like this: 例如,要将程序集中的所有类型写入控制台,可以使用如下代码:
var reference = MetadataReference.CreateFromFile(dllPath);
var compilation = CSharpCompilation.Create(null).AddReferences(reference);
var assemblySymbol = (IAssemblySymbol)compilation.GetAssemblyOrModuleSymbol(reference);
Write(assemblySymbol.GlobalNamespace);
void Write(INamespaceOrTypeSymbol symbol)
{
if (symbol is ITypeSymbol)
Console.WriteLine(symbol);
foreach (var memberSymbol in symbol.GetMembers().OfType<INamespaceOrTypeSymbol>())
{
Write(memberSymbol);
}
}
Roslyn is a compiler. Roslyn是一个编译器。 It takes source code and produces assemblies.
它需要源代码并生成程序集。
To inspect assemblies, you need to use reflection . 要检查装配,您需要使用反射 。
The tool NDepend offers a code model that can be built from assemblies only . NDepend工具提供了一个只能从程序集构建的代码模型 。 No PDB nor source code is required, yet more info can be provided if PDB and source code are available.
不需要PDB或源代码,但如果PDB和源代码可用,则可以提供更多信息。 More explanation on NDepend analysis inputs here .
这里有关于NDepend分析输入的更多解释。
The code model can then be explored through C# LINQ queries . 然后可以通过C#LINQ查询来探索代码模型。 Around 150 predefined code rules are written with such predefined LINQ query.
使用这种预定义的LINQ查询编写大约150个预定义的代码规则 。
The code model built proposes many facilities : code metrics, dependencies, diff since a baseline, state mutability, technical-debt estimation... 构建的代码模型提出了许多功能 :代码度量,依赖关系,自基线以来的差异,状态可变性,技术债务估计......
Disclaimer: I work for NDepend 免责声明:我为NDepend工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.