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

Dmi*_*ryG 3 .net c# wpf winforms .net-core

这是我现在检测它的方法(这种方法基于桌面包类的内部更改):

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Rez*_*aei 5

您可以依赖RuntimeInformation.FrameworkDescription.NET Core测试中使用的内容

//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);
Run Code Online (Sandbox Code Playgroud)

您还可以通过查找TargetFrameworkAttribute程序集来检测正在运行的框架版本(如Rick Strahl 的这篇博客文章):

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