简体   繁体   中英

Ternary operator for 3 conditions

I have using jsReport lib in different enviroments (Windows, OsX and Linux)

In Startup.cs I use this code, to launch library

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

So if it's not Windows platform, he looking for binary for OSX.

But when somebody will use project on Linux he need to change code to:

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

How I can write ternary condition for using Windows as main, and if not it will select between OSX and Linux?

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

But it might be easier just writing 3 if s and doing it like so:

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

You can do something like this:

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

I have not tested it, but it will work,

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

Benefit: we can have any number of conditions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM