如何访问 .csx 脚本中的命令行参数?

Col*_*nic 4 c# c#-interactive csi

我正在使用csi.exeC# 交互式编译器来运行.csx脚本。如何访问提供给我的脚本的任何命令行参数?

csi script.csx 2000
Run Code Online (Sandbox Code Playgroud)

如果您不熟悉 csi.exe,以下是使用信息:

>csi /?
Microsoft (R) Visual C# Interactive Compiler version 1.3.1.60616
Copyright (C) Microsoft Corporation. All rights reserved.

Usage: csi [option] ... [script-file.csx] [script-argument] ...

Executes script-file.csx if specified, otherwise launches an interactive REPL (Read Eval Print Loop).
Run Code Online (Sandbox Code Playgroud)

bin*_*nki 5

CSI 有一个Args全局变量,可以为您解析参数。在大多数情况下,这将为您提供所需的参数,就像您argv在 C/C++ 程序或argsC#Main()签名中访问一样static void Main(string[] args)。

Args有一个类型IList<string>而不是string[]。因此,您将使用.Count来查找参数的数量而不是.Length。

以下是一些示例用法:

#!/usr/bin/env csi
Console.WriteLine($"There are {Args.Count} args: {string.Join(", ", Args.Select(arg => $"“{arg}”"))}");
Run Code Online (Sandbox Code Playgroud)

以及一些示例调用:

ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx
There are 0 args:

ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx hi, these are args.
There are 4 args: “hi,”, “these”, “are”, “args.”

ohnob@DESKTOP-RC0QNSG MSYS ~/AppData/Local/Temp
$ ./blah.csx 'hi, this is one arg.'
There are 1 args: “hi, this is one arg.”
Run Code Online (Sandbox Code Playgroud)


Col*_*nic -1

Environment.GetCommandLineArgs()返回["csi", "script.csx", "2000"]该示例。