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

时间:2021-11-29 19:29:42

I'm writing a Roslyn diagnostic analyzer. I want to tell if System.Collections.Immutable is referenced in RegisterCompilationStartAction before I register any other actions. This is the way I'm going about it so far:

我正在写一个Roslyn诊断分析仪。我想告诉我在注册任何其他操作之前是否在RegisterCompilationStartAction中引用了System.Collections.Immutable。这是我到目前为止的方式:

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? (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? Thanks.

这有效,但我觉得这不是最干净的方法。我可以以某种方式获取与程序集名称对应的MetadataReference,并检查它是否为null,如GetMetadataReference(“System.Collections.Immutable”)== null? (GetMetadataReference不接受字符串,因此实际上不起作用。)如果没有,任何其他更简洁的方法来执行此操作不涉及选择特定类型?谢谢。

1 个解决方案

#1


0  

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;
}

#1


0  

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;
}