.NET 标准库 — 一个库来统治它们。
.NET 标准库功能可能因运行它的 .NET 平台而异:
- .NET 框架
- .NET Core
- 哈马林
如何检查当前运行 .NET 标准库的 .NET 平台?
例如:
// System.AppContext.TargetFrameworkName
// returns ".NETFramework,Version=v4.6.1" for .NET Framework
// and
// returns null for .NET Core.
if (IsNullOrWhiteSpace(System.AppContext.TargetFrameworkName))
// the platform is .NET Core or at least not .NET Framework
else
// the platform is .NET Framework
这是回答这个问题的可靠方法吗(至少对于.NET Framework和.NET Core(?
使用 System.Runtime.InteropServices
命名空间中的 RuntimeInformation.FrameworkDescription
属性。
返回一个字符串,该字符串指示运行应用的 .NET 安装的名称。
该属性返回以下字符串之一:
".NET Core"。
".NET Framework"。
".NET Native"。
.NET Standard 背后的主要思想之一是,除非您正在开发一个非常具体的跨平台库,否则通常您不应该关心底层运行时实现是什么。
但是,如果你真的必须这样做,那么推翻这个原则的一种方法是:
public enum Implementation { Classic, Core, Native, Xamarin }
public Implementation GetImplementation()
{
if (Type.GetType("Xamarin.Forms.Device") != null)
{
return Implementation.Xamarin;
}
else
{
var descr = RuntimeInformation.FrameworkDescription;
var platf = descr.Substring(0, descr.LastIndexOf(' '));
switch (platf)
{
case ".NET Framework":
return Implementation.Classic;
case ".NET Core":
return Implementation.Core;
case ".NET Native":
return Implementation.Native;
default:
throw new ArgumentException();
}
}
}
如果你想更令人震惊,那么你也可以为Xamarin.Forms.Device.RuntimePlatform引入不同的值(更多细节在这里(。