【问题标题】:Ternary operator for 3 conditions3 个条件的三元运算符
【发布时间】:2020-02-17 10:46:08
【问题描述】:

我在不同的环境(Windows、OsX 和 Linux)中使用 jsReport 库

Startup.cs 我使用这段代码来启动库

services.AddJsReport(new LocalReporting()
                .UseBinary(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                    ? JsReportBinary.GetBinary()
                    : jsreport.Binary.OSX.JsReportBinary.GetBinary()).AsUtility()
            .Create());

所以如果不是 Windows 平台,他会寻找 OSX 的二进制文件。

但是当有人在 Linux 上使用项目时,他需要将代码更改为:

services.AddJsReport(new LocalReporting()
            .UseBinary(RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                ? JsReportBinary.GetBinary()
                : jsreport.Binary.Linux.JsReportBinary.GetBinary())

如何编写以 Windows 为主的三元条件,如果不是,它将在 OSX 和 Linux 之间进行选择?

【问题讨论】:

  • 有没有办法识别操作系统?两个贴出的代码sn-p都有OSPlatform.Windows查看平台?
  • ":"后面的"if not"部分可以再写一个三元运算,判断是OSX还是Linux,然后返回对应的。

标签: c# asp.net asp.net-core ternary-operator


【解决方案1】:
services.AddJsReport(new LocalReporting()
    .UseBinary(
        RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
        ? JsReportBinary.GetBinary()
        : RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
            ? Jsreport.Binary.Linux.JsReportBinary.GetBinary()
            : Jsreport.Binary.OSX.JsReportBinary.GetBinary())
    .Create();

但写 3 ifs 并这样做可能会更容易:

// I don't know the exact type, put the correct one here if it isn't this
JsReportBinary binary;

if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
    binary = JsReportBinary.GetBinary();
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
    binary = Jsreport.Binary.Linux.JsReportBinary.GetBinary();
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)
    binary = Jsreport.Binary.OSX.JsReportBinary.GetBinary());
else
    binary = null;

services.AddJsReport(new LocalReporting().UseBinary(binary).Create());

【讨论】:

  • @EugeneSukh 没问题,在这里为您提供帮助。顺便说一句,我刚刚用另一种(我认为更容易阅读)的方式更新了我的答案。如果这解决了您的问题,请不要忘记用绿色复选标记将答案标记为已接受,以便将来的观众更容易发现它
【解决方案2】:

你可以这样做:

RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
      ? JsReportBinary.GetBinary() :
    RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ?
   jsreport.Binary.OSX.JsReportBinary.GetBinary()  : 
   jsreport.Binary.Linux.JsReportBinary.GetBinary())

【讨论】:

    【解决方案3】:

    我没有测试过,但它会工作,

    services.AddJsReport(new LocalReporting()
                    .UseBinary((RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && JsReportBinary.GetBinary())
                               || (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && Jsreport.Binary.Linux.JsReportBinary.GetBinary())
                               || (Jsreport.Binary.OSX.JsReportBinary.GetBinary()))
                    .Create();
    

    好处:我们可以有任意数量的条件。

    【讨论】:

      猜你喜欢
      • 2020-01-18
      • 1970-01-01
      • 1970-01-01
      • 2012-09-14
      • 2018-03-13
      • 2011-06-26
      • 2021-05-13
      • 1970-01-01
      • 2023-04-11
      相关资源
      最近更新 更多