在构建应用程序时,我需要传递一组常量以在运行时使用。例如,我们想将一些字符串值“缝制”到应用程序中,这在组装时是已知的。在C ++世界中,我非常简单地使用定义和编译器选项解决了这些问题。但是在.Net define中,除了true / false之外没有其他值,即它们是否被识别。据我了解,他们的目标是最简单的条件编译。谁在乎解决方案,欢迎来关注。拜访我的第一个想法是在构建之前通过模板生成一个包含常量的文件,但我想在不涉及模板引擎的大炮的情况下进行操作。经过一番搜索,我发现了一个有趣的事实。.Net具有属性机制。这些属性可以保留在类,方法,字段以及各种不同的实体上。事实证明,它可以挂在整个组件上。在项目文件(.csproj)中,可以在汇编过程中为这些属性设置值。在MSBuild中,您可以通过属性机制从外部传递参数。似乎一切正常,您必须尝试。创建一个新的控制台应用程序:% mkdir Example && cd Example
% dotnet new console
我们使用属性定义创建文件ExampleAttribute.cs。using System;
namespace Example
{
[AttributeUsage(AttributeTargets.Assembly)]
public class ExampleAttribute : Attribute
{
public string Value { get; set; }
public ExampleAttribute(string value)
{
Value = value;
}
}
}
接下来,将Example.csproj文件简化为以下形式。我添加了评论,以便使更改的本质清晰明了。<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
<RootNamespace>Example</RootNamespace>
<ExampleValue>default</ExampleValue>
</PropertyGroup>
<ItemGroup>
<AssemblyAttribute Include="Example.ExampleAttribute">
<_Parameter1>$(ExampleValue)</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
</Project>
好吧,实际上,可以在Project.cs中获得运行时的价值using System;
using System.Reflection;
namespace Example
{
class Program
{
static void Main(string[] args)
{
var assembly = Assembly.GetExecutingAssembly();
var attr = (ExampleAttribute) assembly.GetCustomAttribute(typeof(ExampleAttribute));
Console.WriteLine($"Assembly attribute value = '{attr.Value}'");
}
}
}
因此,我们将组装并运行以查看所获得的内容。% dotnet build .
% dotnet run --no-build .
Assembly attribute value = 'default'
现在带有参数:% dotnet build . /p:ExampleValue="NOT DEFAULT"
% dotnet run --no-build .
Assembly attribute value = 'NOT DEFAULT'
瞧,目标已经实现。用于健康。