[英]How to detect which .NET runtime is being used (MS vs. Mono)?
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?有没有更好的方法来检查当前运行时?
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我相信你会有更多的问题,所以值得查看本指南和单声道论坛
您可以像这样检查 Mono 运行时
bool IsRunningOnMono = (Type.GetType ("Mono.Runtime") != null);
随着 C# 6 的出现,现在可以将其转换为仅获取属性,因此实际检查只进行一次。
internal static bool HasMono { get; } = Type.GetType("Mono.Runtime") != null;
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.正如@ahmet alp balkan 提到的,如果您经常调用它,缓存在这里很有用。 By wrapping it in a Lazy<bool>
, the reflection call only happens once.通过将其包装在Lazy<bool>
中,反射调用只发生一次。
just run the below code..只需运行以下代码..
static bool IsMicrosoftCLR()
{
return (Type.GetType ("Mono.Runtime") == null)
}
System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription提供运行应用程序的 .NET 安装的名称和版本,例如“单声道版本”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.