[英]Can I define constants based on the runtime identifier in .NET Core?
I have a .NET Core Console application. 我有一个.NET Core Console应用程序。 My goal here is to be able to conditionally DLLImport
a function and call it, but only on Windows runtimes. 我的目标是能够有条件地DLLImport
一个函数并调用它,但只能在Windows运行时。
I thought maybe if I could access the runtime identifier in the csproj
file, I could conditionally define a constant for that runtime, then in my c# I could surround the DLLImport and calls in #if
/ #endif
blocks. 我想如果我可以访问csproj
文件中的运行时标识符,我可以有条件地为该运行时定义一个常量,然后在我的c#中我可以包围DLLImport并调用#if
/ #endif
块。
Is it possible to set compilation constants within a csproj
based on the runtime the project is being built for? 是否可以根据构建项目的运行时在csproj
设置编译常量? This is specifically for an SDK-style Project format (that starts with <Project Sdk="Microsoft.NET.Sdk">
) that is targeting .NET Core. 这是针对以.NET风格为目标的SDK风格的项目格式(以<Project Sdk="Microsoft.NET.Sdk">
)。
Note: this question gets close, but is for project.json
style projects. 注意: 这个问题很接近,但是对于project.json
样式项目。
Alternately, is there a better approach to accomplish my goal? 或者,是否有更好的方法来实现我的目标?
If you are building and publishing for different runtimes by passing different --runtime
options (MSBuild property RuntimeIdentifier
), you can condition on that property in the csproj file (allowing you to use #if BUILT_FOR_WINDOWS
in your C# code): 如果您通过传递不同的--runtime
选项(MSBuild属性RuntimeIdentifier
)来构建和发布不同的运行时,则可以在csproj文件中对该属性进行条件限制(允许您在C#代码中使用#if BUILT_FOR_WINDOWS
):
<PropertyGroup>
<DefineConstants Condition="'$(RuntimeIdentifier)' == 'win-x64'">$(DefineConstants);BUILT_FOR_WINDOWS</DefineConstants>
</PropertyGroup>
However you can also test the current OS at run time using: 但是,您还可以使用以下命令在运行时测试当前操作系统:
using System.Runtime.InteropServices;
…
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// call windows function here
}
else
{
// do something else here
}
As long as a function marked with [DllImport(…)]
is not called on an OS where the library / method cannot be found, there shouldn't be any problems. 只要在无法找到库/方法的OS上调用标有[DllImport(…)]
的函数,就不会有任何问题。 Do note that DllImport()
can also probe for different libraries depending on the os - so DllImport("foo")
would check for foo.dll
, foo.dylib
, libfoo.so
etc. 请注意, DllImport()
也可以根据操作系统探测不同的库 - 所以DllImport("foo")
会检查foo.dll
, foo.dylib
, libfoo.so
等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.