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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 06:45:48

问题


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

The .NET Standard Library functionality may vary depending on the .NET platform that runs it:

  • .NET Framework
  • .NET Core
  • Xamarin

How to check the .NET platform where the .NET Standard library currently runs?

For example:

// 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

Is it reliable way to answer the question (at least for .NET Framework and .NET Core)?


回答1:


Use the RuntimeInformation.FrameworkDescription Property from the System.Runtime.InteropServices namespace.

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".




回答2:


Well.. one of the main ideas behind .NET Standard is that unless you're developing a very specific cross-platform library then in general you should not be caring what the underlying runtime implementation is.

But if you really must then one way of overriding that principle is this:

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();
      }
   }
}

And if you want to be even more egregious, then you can bring in the different values for Xamarin.Forms.Device.RuntimePlatform also (with more details here).



来源:https://stackoverflow.com/questions/48259320/how-to-determine-the-net-platform-that-runs-the-net-standard-class-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!