zoukankan      html  css  js  c++  java
  • 利用 RuntimeInformation 来构建运行环境的区别依赖

    场景:

    构建应用程序时,需要对运行的环境进行判断,或者分别设置。

    比如:NETCORE 在跨平台 程序某些特定的目录的指定,在Linux/windows/mac/os/android 环境下运行,指定的目录有所区别. 利用 RuntimeInformation

    就很容易构建我们对运行环境的判断。


    下面我们给出相对应的场景例子:程序支持 跨平台运行,程序的日志的存放目录,用户临时文件目录进行 预先指定。

    1:构建多平台运行的维护的公共类 PlatformArbiter:

    public class PlatformArbiter
        {
            public T GetValue<T>(Func<T> windowsValueProvider, Func<T> linuxValueProvider, Func<T> osxValueProvider, Func<T> defaultValueProvider)
            {
                return RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                    ? windowsValueProvider()
                    : RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
                        ? linuxValueProvider()
                        : RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
                            ? osxValueProvider()
                            : defaultValueProvider();
            }
    
            public void Invoke(Action windowsValueProvider, Action linuxValueProvider, Action osxValueProvider, Action defaultValueProvider)
            {
                var invoker = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                    ? windowsValueProvider
                    : RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
                        ? linuxValueProvider
                        : RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
                            ? osxValueProvider
                            : defaultValueProvider;
                invoker();
            }

    2:使用 PlatformArbiter

    private readonly PlatformIArbiter _platformArbiter;
    
            public string TmpDirectory => _platformArbiter.GetValue(
                () => Path.Combine(Environment.GetEnvironmentVariable("USERPROFILE"), "AppData\\Local\\Temp"),
                () => "/tmp",
                () => "/tmp",
                () => "/tmp");
    
            public string DotnetDirectory => _platformArbiter.GetValue(
                () => Path.Combine("C:\\Progra~1", "dotnet"),
                () => Path.Combine("/usr/local/share", "dotnet"),
                () => Path.Combine("/usr/local/share", "dotnet"),
                () => Path.Combine("/usr/local/share", "dotnet"));
  • 相关阅读:
    Boost之使用篇(1)
    Lucene 3.0.0细节初窥(1)深入探索Lucene的consumer与processor
    整理一点关于Lucene的学习资料, 方便自己与别人查看
    使用Lucene 3.0.0的结构遍历TokenStream的内容.
    [原创]如何写一个完善的c++异常处理类
    Lucene 3.0.0 的TokenStream与Analyzer
    Lucene 3.0.0 之样例解析(4)IndexFiles.java
    贝叶斯、概率分布与机器学习
    Lucene用c++重写的详细安排
    Lucene 3.0.0的细节初窥(2)研究在索引过程中的缓存
  • 原文地址:https://www.cnblogs.com/davidchild/p/14840888.html
Copyright © 2011-2022 走看看