如何指定多个项目的 InternalsVisibleTo
InternalsVisibleTo 属性允许你指定一个或多个程序集,这些程序集可以访问当前程序集中的内部类型。经常在进行单元测试时使用,例如,你可以在一个项目中定义一个内部类型,然后在另一个项目中进行单元测试。本文将介绍如何指定多个项目的 InternalsVisibleTo,从而不需要在每个项目中都指定一遍。
代码演示
假如我们有一个项目,名称为 TestProject1。则我们需要在 TestProject1 中指定 InternalsVisibleTo 属性,如下所示:
[assembly: InternalsVisibleTo("TestProject1.Tests")]
但其实,我们也可以在 TestProject1.csproj 中指定 InternalsVisibleTo 属性,如下所示:
<Project> <ItemGroup> <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute"> <_Parameter1>TestProject1.Tests</_Parameter1> <!-- We use the value of AssemblyName to declare the value of the attribute --> </AssemblyAttribute> </ItemGroup> </Project>
既然如此,我们便可以使用 Directory.Build.props 文件来指定多个项目的 InternalsVisibleTo 属性,如下所示:
<Project> <ItemGroup> <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleToAttribute"> <_Parameter1>$(AssemblyName).Tests</_Parameter1> <!-- We use the value of AssemblyName to declare the value of the attribute --> </AssemblyAttribute> </ItemGroup> </Project>
这样,所有的项目都会自动指定 InternalsVisibleTo 属性,而不需要在每个项目中都指定一遍。
总结
本文介绍了如何指定多个项目的 InternalsVisibleTo 属性,从而不需要在每个项目中都指定一遍。
参考资料
- directory.build.props[1]
- Adding AssemblyMetadataAttribute using new SDK project, with MSBuild[2]
- 本文作者: newbe36524
- 本文链接: https://www.newbe.pro/ChatAI/0x016-How-to-InternalsVisibleTo-for-multiple-projects/
- 版权声明: 本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
参考资料
[1]directory.build.props: https://learn.microsoft.com/visualstudio/msbuild/customize-your-build?view=vs-2019&WT.mc_id=DX-MVP-5003606#directorybuildprops-and-directorybuildtargets
[2]Adding AssemblyMetadataAttribute using new SDK project, with MSBuild: https://stu.dev/adding-assemblymetadataattribute-using-new-sdk-project-with-msbuild/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了