问题
.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