首页 > 解决方案 > 3 个条件的三元运算符

问题描述

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

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 之间进行选择?

标签: c#asp.netasp.net-coreternary-operator

解决方案


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());

推荐阅读