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

8

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

csi script.csx 2000

如果您不熟悉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).

2
可能是如何使用CSI.exe脚本参数的重复问题。 - binki
3个回答

12

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

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

以下是一些示例用法:

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

还有一些样例调用:

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.”

1
这是我的脚本:

    var t = Environment.GetCommandLineArgs();
    foreach (var i in t)
        Console.WriteLine(i);

传递参数给 csx 的方法如下:
    scriptcs hello.csx -- arg1 arg2 argx

打印输出:

    hello.csx
    --
    arg1
    arg2
    argx

关键是在 csx 和 script 参数之间使用 '--'。


@binki 这应该是一个独立的答案,而不是评论。 - Chris Charabaruk
1
@ChrisCharabaruk 我已将它提升为回答并删除了我的评论。谢谢! - binki

-1

Environment.GetCommandLineArgs() 返回 ["csi", "script.csx", "2000"],以此为例。


https://dev59.com/DFoT5IYBdhLWcg3w4SpQ#38061368 避免了尝试猜测脚本参数开始位置的问题,因此我不建议使用此答案中的方法。 - binki

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接