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"));
  • 相关阅读:
    poj 1840(五元三次方程组)
    Selenium(二)开发环境的搭建
    Selenium(一)自动化测试简介
    (二)AppScan使用教程
    (一)AppScan的安装及破解
    (一)python3.7的安装
    读完《大道至简》后的反思
    BZOJ3585: mex
    BZOJ3544: [ONTAK2010]Creative Accounting
    BZOJ3531: [Sdoi2014]旅行
  • 原文地址:https://www.cnblogs.com/davidchild/p/14840888.html
Copyright © 2011-2022 走看看