我可以拒绝从应用它的程序集外部访问程序集属性吗?

Can I deny access to an Assembly attribute from outside the assembly it is applied to?

我能否将程序集属性(如 [assembly: AssemblyMetadata("key", "value")])标记为 private/internal 以使其只能从应用它的程序集中访问?

背景: 我刚刚测试了一种技术,通过 AssemblyMetadata 属性和自定义 msbuild 目标获取代码中的一些构建信息(例如解决方案目录),方法是将以下 class 添加到项目中,将 msbuild 目标添加到 * .csproj 文件:

static class BuildEnvironment
{
    static string _solutionDir;

    public static string SolutionDirectory
    {
        get
        {
            if (_solutionDir == null)
                _solutionDir = Initialize();
            return _solutionDir;

            string Initialize()
            {
                var metadata = typeof(BuildEnvironment).GetTypeInfo().Assembly.GetCustomAttributes<AssemblyMetadataAttribute>();
                return metadata.FirstOrDefault((x) => x.Key == "SolutionDir")?.Value ?? string.Empty;
            }
        }
    }
}


<Target Name="GenerateBuildEnvironment" BeforeTargets="CoreCompile">
    <ItemGroup>
        <AssemblyAttributes Include="AssemblyMetadata">
            <_Parameter1>SolutionDir</_Parameter1>
            <_Parameter2>$(SolutionDir)</_Parameter2>
        </AssemblyAttributes>
    </ItemGroup>
    <WriteCodeFragment AssemblyAttributes="@(AssemblyAttributes)" Language="C#" OutputDirectory="$(IntermediateOutputPath)">
        <Output TaskParameter="OutputFile" ItemName="Compile" />
    </WriteCodeFragment>
</Target>

Can I mark an assembly attribute (like [assembly: AssemblyMetadata("key", "value")]) as private/internal to make it only accessible from within the assembly it is applied to?

没有。元数据的要点是它需要可以从 .NET 本身或外部工具(例如 ReflectorJetBrains DotPeek 读取。元数据定义为 public。隐藏它达不到目的。

如果您希望此类信息不公开,请不要使用 .NET 程序集属性。您可以将其存储为资源并使用您喜欢的保护方法对其进行保护。