gpt4 book ai didi

c# - 如何在运行时读取给定项目中的 MSBuild 属性?

转载 作者:行者123 更新时间:2023-12-05 01:15:07 26 4
gpt4 key购买 nike

我想访问单元测试中的 MSBuild 变量,这是一个 .NET 4.5 类库项目(经典 csproj),但我找不到任何讨论将值从 MSBuild 传递到执行上下文的方法的文章。

我想过在编译期间设置一个环境变量,然后在执行期间读取该环境变量,但这似乎需要一个自定义任务来设置环境变量值,我有点担心变量的范围(理想情况下,我只希望它对当前正在执行的项目可用,而不是全局可用)。

是否有在运行时从 DLL 项目中读取 MSBuild 属性的已知解决方案? MSBuild 属性可以在执行期间以某种方式“作为参数传递”吗?

最佳答案

我最终通过使用 .Net Core 项目中默认使用的相同代码生成任务使其工作。唯一的区别是我必须在 csproj 文件中手动添加 Target 才能使其工作,因为代码创建不是框架项目的标准:

<Target Name="BeforeBuild">
<ItemGroup>
<AssemblyAttributes Include="MyProject.SolutionFileAttribute">
<_Parameter1>$(SolutionPath)</_Parameter1>
</AssemblyAttributes>
</ItemGroup>
<WriteCodeFragment AssemblyAttributes="@(AssemblyAttributes)" Language="C#" OutputDirectory="$(IntermediateOutputPath)" OutputFile="SolutionInfo.cs">
<Output TaskParameter="OutputFile" ItemName="Compile" />
<Output TaskParameter="OutputFile" ItemName="FileWrites" />
</WriteCodeFragment>
</Target>

带有 CompileFileWrites 的行可以很好地与 clean 等配合使用(请参阅我上面评论中的链接答案)。其他一切都应该足够直观。

当项目编译时,一个自定义属性被添加到程序集中,然后我可以使用正常反射检索:

Assembly
.GetExecutingAssembly()
.GetCustomAttribute<SolutionFileAttribute>()
.SolutionFile

这非常有效,让我可以避免对解决方案文件进行任何硬编码搜索。

关于c# - 如何在运行时读取给定项目中的 MSBuild 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56835671/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com