如何检测正在使用哪个.NET运行时(MS与Mono)?
我想知道在程序的执行过程中,它是使用Mono运行时还是Microsoft运行时执行的。
我目前使用下面的代码来确定我是否在MS CLR上:
static bool IsMicrosoftCLR() { return RuntimeEnvironment.GetRuntimeDirectory().Contains("Microsoft"); } 但是,这有点依赖于运行时的安装文件夹,我不确定这是否适用于所有安装。
有没有更好的方法来检查当前的运行时间?
从Mono项目指南移植Winforms应用程序 :
 public static bool IsRunningOnMono () { return Type.GetType ("Mono.Runtime") != null; } 
我相信你会有更多的问题,所以值得检查本指南和单论坛
你可以检查单声道运行时像这样
 bool IsRunningOnMono = (Type.GetType ("Mono.Runtime") != null); 
只需运行下面的代码
 static bool IsMicrosoftCLR() { return (Type.GetType ("Mono.Runtime") == null) } 
随着C#6的出现,现在可以变成一个只读属性,所以实际的检查只做一次。
 internal static bool HasMono { get; } = Type.GetType("Mono.Runtime") != null; 
以下是我在项目中使用的caching版本:
 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; } } 
 正如@ahmet alp balkan所提到的那样,如果你频繁地调用它,caching在这里很有用。 通过将其包装在Lazy<bool> ,reflection调用只发生一次。