C# 如何检测正在使用哪个 .NET 运行时(MS 与 Mono)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/721161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 22:27:30  来源:igfitidea点击:

How to detect which .NET runtime is being used (MS vs. Mono)?

c#monoclr

提问by Dirk Vollmar

I would like to know during execution of a program whether it is being executed using the Mono runtime or the Microsoft runtime.

我想知道在程序执行期间它是使用 Mono 运行时还是 Microsoft 运行时执行的。

I'm currently using the following code to determine whether I'm on a MS CLR:

我目前正在使用以下代码来确定我是否在 MS CLR 上:

static bool IsMicrosoftCLR()
{
    return RuntimeEnvironment.GetRuntimeDirectory().Contains("Microsoft");
}

However, this is somewhat dependent on the installation folder of the runtime and I'm not sure whether this will work on all installations.

但是,这在某种程度上取决于运行时的安装文件夹,我不确定这是否适用于所有安装。

Is there a better way to check for the current runtime?

有没有更好的方法来检查当前运行时?

采纳答案by Mystic

From the Mono Project's Guide to Porting Winforms Applications:

从 Mono Project's Guide to Porting Winforms Applications

public static bool IsRunningOnMono ()
{
    return Type.GetType ("Mono.Runtime") != null;
}

I'm sure you'll have a lot more questions, so worth checking this guide and the mono-forums

我相信你会有更多的问题,所以值得查看本指南和单一论坛

回答by Alex

You can check for the Mono Runtime Like this

您可以像这样检查 Mono 运行时

bool IsRunningOnMono = (Type.GetType ("Mono.Runtime") != null);

回答by Binoj Antony

just run the below code..

只需运行下面的代码..

static bool IsMicrosoftCLR()
{
    return (Type.GetType ("Mono.Runtime") == null)
}

回答by Mystic

With the advent of C# 6, this can now be turned into a get-only property, so the actual check is only done once.

随着 C# 6 的出现,这现在可以变成一个 get-only 属性,因此实际检查只执行一次。

internal static bool HasMono { get; } = Type.GetType("Mono.Runtime") != null;

回答by Nate Barbettini

Here's a version with caching that I'm using in my project:

这是我在项目中使用的带有缓存的版本:

public static class PlatformHelper
{
    private static readonly Lazy<bool> IsRunningOnMonoValue = new Lazy<bool>(() =>
    {
        return Type.GetType("Mono.Runtime") != null;
    });

    public static bool IsRunningOnMono()
    {
        return IsRunningOnMonoValue.Value;
    }
}

As @ahmet alp balkan mentioned, caching is useful here if you're calling this frequently. By wrapping it in a Lazy<bool>, the reflection call only happens once.

正如@ahmet alp balkan 所提到的,如果您经常调用它,缓存在这里很有用。通过将它包装在 a 中Lazy<bool>,反射调用只发生一次。