[英]How to obtain build configuration at runtime?
有谁知道如何在 C# 代码中获取当前的构建配置$(Configuration)
?
如果你卸载你的项目(在右键菜单中)并在</Project>
标签之前添加它,它将保存一个包含你的配置的文件。 然后您可以将其读回以在您的代码中使用。
<Target Name="BeforeBuild">
<WriteLinesToFile File="$(OutputPath)\env.config"
Lines="$(Configuration)" Overwrite="true">
</WriteLinesToFile>
</Target>
你不能,不是真的。 您可以做的是定义一些“条件编译符号”,如果您查看项目设置的“构建”页面,您可以在那里进行设置,以便您可以编写#if 语句来测试它们。
调试符号会自动注入(默认情况下,可以关闭)用于调试版本。
所以你可以写这样的代码
#if DEBUG
RunMyDEBUGRoutine();
#else
RunMyRELEASERoutine();
#endif
但是,除非您有充分的理由,否则不要这样做。 在调试和发布版本之间以不同行为工作的应用程序对任何人都没有好处。
可以使用条件编译符号来实现这一点。 您可以在“属性”>“构建设置”窗格中为每个项目定义自定义符号,并使用 #if 指令在代码中测试它们。
示例显示如何定义符号 UNOEURO 以及如何在代码中使用它。
bool isUnoeuro = false;
#if UNOEURO
isUnoeuro = true;
#endif
.NET 中有AssemblyConfigurationAttribute 。 您可以使用它来获取构建配置的名称
var assemblyConfigurationAttribute = typeof(CLASS_NAME).Assembly.GetCustomAttribute<AssemblyConfigurationAttribute>();
var buildConfigurationName = assemblyConfigurationAttribute?.Configuration;
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
</startup>
<appSettings>
<add key="Build" value="" />
</appSettings>
</configuration>
<?xml version="1.0" encoding="utf-8"?>
<!--For more information on using transformations see the web.config examples at http://go.microsoft.com/fwlink/?LinkId=214134. -->
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<appSettings>
<add key="Build" value="Debug" xdt:Transform="Replace" xdt:Locator="Match(key)"/>
</appSettings>
</configuration>
ConfigurationManager.AppSettings["Build"]
您可以使用带有条件属性的通用静态方法来设置标志以检测 DEBUG 或 RELEASE 模式。 只有在 DEBUG 模式下运行时才会调用 SetDebugMode 方法,否则它会被 Runtime 忽略。
public static class AppCompilationConfiguration
{
private static bool debugMode;
private static bool IsDebugMode()
{
SetDebugMode();
return debugMode;
}
//This method will be loaded only in the case of DEBUG mode.
//In RELEASE mode, all the calls to this method will be ignored by runtime.
[Conditional("DEBUG")]
private static void SetDebugMode()
{
debugMode = true;
}
public static string CompilationMode => IsDebugMode() ? "DEBUG" : "RELEASE";
}
您可以在如下代码中调用它
Console.WriteLine(AppCompilationConfiguration.CompilationMode);
我不相信您可以在编译时将其注入程序集,但实现它的一种方法是使用 MSBuild 并将其添加到应用程序的配置文件中。
请参阅有关如何使用 MSBuild 执行多环境配置文件的博客文章 - http://adeneys.wordpress.com/2009/04/17/multi-environment-config/
或者,您可以编写一个 MSBuild 任务,该任务将编辑某个编译文件(您的 C# 或 VB 文件)并在BeforeBuild
任务中运行该BeforeBuild
。 这会相当棘手,因为您需要确定将其注入文件的位置,但是如果您设置了某种标记化,您应该能够做到。 我也怀疑它会漂亮!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.