如何知道我是在 .NET Framework 还是 .NET Core 下运行

bar*_*iro 9 c# .net-assembly .net-core

假设我有一个 Nuget 库,它编译为netstandard2.0支持netcoreapp2.1net471.

现在,在编译时,我不知道我是否在net471netcoreapp2.1或下运行(我强调这一点是因为我不能将我的 dll 编译为 和netstandard2.0netstandard因为net471如果调用程序集netstandard2.0,我仍然不知道什么关于入口组件)。

我如何在运行时知道我正在运行哪个 TargetFramwork?


我知道有一个这样的解决方案:

Assembly.GetEntryAssembly()?
    .GetCustomAttribute<TargetFrameworkAttribute>()?
    .FrameworkName
Run Code Online (Sandbox Code Playgroud)

但是,如果您在 MSTest 和 中运行此net471命令Assembly.GetEntryAssembly() == null,那么我不想破坏使用我的 Nuget 的项目中的测试。

juF*_*uFo 12

调用System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription会给你一个字符串:

字符串

".NET" (for .NET 5 and later versions)
".NET Core" (for .NET Core 1.0 - 3.1)
".NET Framework"
".NET Native"`
Run Code Online (Sandbox Code Playgroud)

https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.runtimeinformation.frameworkdescription?view=net-6.0