【问题标题】:How to determine the .NET platform that runs the .NET Standard class library?如何确定运行 .NET Standard 类库的 .NET 平台?
【发布时间】:2018-06-23 20:49:00
【问题描述】:

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

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

  • .NET 框架
  • .NET Core
  • Xamarin

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

【问题讨论】:

    标签: c# .net-core .net-standard .net-standard-2.0


    【解决方案1】:

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

    返回一个字符串,该字符串指示运行应用程序的 .NET 安装的名称。

    该属性返回以下字符串之一:

    • “.NET 核心”。

    • “.NET 框架”。

    • “.NET 原生”。

    【讨论】:

    • 可能想通过Contains 进行检查,因为对于 .NET Framework 4.8,至少它会返回完整的版本信息,即。 .NET Framework 4.8.4420.0
    【解决方案2】:

    嗯.. 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 引入不同的值(更多细节here)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多