如何检测我的库是否在.Net Core 3 Desktop Package下运行

时间:2018-12-07 06:18:43

标签: c# .net wpf winforms .net-core

这是我现在可以检测到的方式(此方法基于Desktop Package类中的内部更改):

public static class FrameworkVersions {
    static readonly bool f_nativeMatrix_Exists;
    static FrameworkVersions() {
        f_nativeMatrix_Exists= typeof(System.Drawing.Drawing2DMatrix)
            .GetField("nativeMatrix", BindingFlags.Instance | BindingFlags.NonPublic) != null;
    }
    public static bool IsNetCore3DesktopPackage {
        get{ return !f_nativeMatrix_Exists; }
    }
}

存在最好的方法吗?请分享您的经验。

1 个答案:

答案 0 :(得分:2)

您可以像在.NET Core RuntimeInformation.FrameworkDescription中一样使用tests

//using System.Runtime.InteropServices;
bool IsFullFramework = RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework",
    StringComparison.OrdinalIgnoreCase);
bool IsNetNative = RuntimeInformation.FrameworkDescription.StartsWith(".NET Native",
    StringComparison.OrdinalIgnoreCase);
bool IsNetCore = RuntimeInformation.FrameworkDescription.StartsWith(".NET Core", 
    StringComparison.OrdinalIgnoreCase);

您还可以通过找到程序集的TargetFrameworkAttribute(例如Rick Strahl的blog post)来检测运行中的框架版本:

//using System.Reflection;
//using System.Runtime.Versioning;
var framework = Assembly.GetEntryAssembly()?
    .GetCustomAttribute<TargetFrameworkAttribute>()?
    .FrameworkName;
MessageBox.Show(framework);