简体   繁体   English

Roslyn:如何判断编译中是否引用了特定的程序集?

[英]Roslyn: How do I tell if a particular assembly is referenced in a Compilation?

I'm writing a Roslyn diagnostic analyzer. 我正在写一个Roslyn诊断分析仪。 I want to tell if System.Collections.Immutable is referenced in RegisterCompilationStartAction before I register any other actions. 我想告诉我在注册任何其他操作之前是否在RegisterCompilationStartAction引用System.Collections.Immutable This is the way I'm going about it so far: 这是我到目前为止的方式:

context.RegisterCompilationStartAction(compilationStartContext =>
{
    var compilation = compilationStartContext.Compilation;
    if (compilation.GetTypeByMetadataName("System.Collections.Immutable.ImmutableArray`1") == null)
    {
        return;
    }

    ...
});

This works, but I don't feel it's the cleanest way to do this. 这有效,但我觉得这不是最干净的方法。 Can I somehow get a MetadataReference corresponding to the assembly name instead and check if it's null, like GetMetadataReference("System.Collections.Immutable") == null ? 我可以以某种方式获取与程序集名称对应的MetadataReference ,并检查它是否为null,如GetMetadataReference("System.Collections.Immutable") == null ( GetMetadataReference doesn't accept a string, so that doesn't actually work.) If not, any other cleaner way to do this that doesn't involve picking out a particular type? GetMetadataReference不接受字符串,因此实际上不起作用。)如果没有,任何其他更简洁的方法来执行此操作不涉及选择特定类型? Thanks. 谢谢。

Instead of searching for the type you could simply search through the References and resolve the MetadataReference to check whether a specific assembly is included within a Project: 您可以直接搜索引用并解析MetadataReference以检查项目中是否包含特定程序集,而不是搜索类型:

if(!compilation.References.Any(reference => 
        compilation.GetAssemblyOrModuleSymbol(reference)
        .Name == "System.Collections.Immutable"))
{
    return;
}

暂无
暂无

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

相关问题 Roslyn编译:类型在未引用的程序集中定义 - Roslyn compilation: type is defined in an assembly that is not referenced 如何在Roslyn的某个语法节点上判断变量是否在范围内? - How do I tell if a variable is in scope at some syntax node with Roslyn? 有没有办法使用Roslyn中的Compilation对象从引用的程序集中获取程序集级属性? - Is there a way to get assembly level attributes from referenced assemblies using the Compilation object in Roslyn? 如何在Visual Studio中单步执行引用的程序集? - How do I step through a referenced assembly in Visual Studio? 如何删除 Roslyn? - How do I remove Roslyn? 如何从编译的引用lib中判断调用程序集是否处于DEBUG模式 - How to tell if calling assembly is in DEBUG mode from compiled referenced lib 如何将加载的程序集提供给C#中的Roslyn工作区 - How can I feed a loaded Assembly to a Roslyn Workspace in C# 未使用(和引用)的程序集上的程序集引用错误,为什么会出现此错误? - Assembly reference error on not used (and referenced) assembly, why do I this error? 除非我首先在该程序集中实例化一个类,否则无法对引用的程序集进行Assembly.Load(String)。 怎么解决? - Can't do Assembly.Load(String) with a referenced assembly unless I instantiate a class within that assembly first. How to solve? 如何使用 Roslyn 声明 var 变量? - How do I declare a var variable with Roslyn?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM