如何确定运行 .NET Standard class 库的 .NET 平台?

How to determine the .NET platform that runs the .NET Standard class library?

.NET Standard Library — One library to rule them all.

.NET 标准库功能可能因运行它的 .NET 平台而异:

如何查看当前运行 .NET Standard 库的 .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)?

嗯.. main ideas behind .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 also (with more details here).

引入不同的值

使用 System.Runtime.InteropServices 命名空间中的 RuntimeInformation.FrameworkDescription 属性。

Returns a string that indicates the name of the .NET installation on which an app is running.

The property returns one of the following strings:

  • ".NET Core".

  • ".NET Framework".

  • ".NET Native".