代码之家  ›  专栏  ›  技术社区  ›  Dirk Vollmar

如何检测正在使用的.NET运行时(MS与Mono)?

  •  45
  • Dirk Vollmar  · 技术社区  · 15 年前

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

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

    是否有更好的方法检查当前运行时?

    5 回复  |  直到 15 年前
        1
  •  78
  •   Mystic    15 年前

    来自Mono项目的 Guide to Porting Winforms Applications :

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

    mono-forums

        2
  •  24
  •   Rowland Shaw    15 年前

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

    bool IsRunningOnMono = (Type.GetType ("Mono.Runtime") != null);
    
        3
  •  13
  •   user502255 user502255    8 年前

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

    internal static bool HasMono { get; } = Type.GetType("Mono.Runtime") != null;
    
        4
  •  8
  •   Binoj Antony    15 年前

    只需运行下面的代码。。

    static bool IsMicrosoftCLR()
    {
        return (Type.GetType ("Mono.Runtime") == null)
    }
    
        5
  •  8
  •   Nate Barbettini    9 年前

    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所提到的,如果您经常调用缓存,那么这里的缓存非常有用。把它包在一个盒子里 Lazy<bool> ,反射调用只发生一次。