注意:@adabru 下面的回答使我的解决方案过时,除非您使用的是较旧的单声道平台。
C# 脚本可以像 Python 和 Perl 脚本一样从 bash 命令行运行,但需要一点 bash 魔法才能使其工作。正如上面提到的Corey,你必须首先在你的机器上安装Mono。然后,将以下代码保存在 Linux 机器上的可执行 bash 脚本中:
if [ ! -f "$1" ]; then
dmcs_args=$1
shift
else
dmcs_args=""
fi
script=$1
shift
input_cs="$(mktemp)"
output_exe="$(mktemp)"
tail -n +2 $script > $input_cs
dmcs $dmcs_args $input_cs -out:${output_exe} && mono $output_exe $@
rm -f $input_cs $output_exe
假设您将上述脚本保存为 /usr/bin/csexec,下面是一个示例 C#“脚本”:
#!/usr/bin/csexec -r:System.Windows.Forms.dll -r:System.Drawing.dll
using System;
using System.Drawing;
using System.Windows.Forms;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello Console");
Console.WriteLine("Arguments: " + string.Join(", ", args));
MessageBox.Show("Hello GUI");
}
}
将上述代码保存到“hello.cs”等文件中,使其可执行,将第一行更改为指向之前保存的 bash 脚本,然后执行它,您应该会看到以下输出以及一个对话框说“你好 GUI”:
bash-4.2$ ./hello.cs foo bar baz
Hello Console
Arguments: foo, bar, baz
请注意,GUI 要求您处于运行级别 5。这是一个在纯文本控制台上运行的更简单的 C# 脚本:
#!/usr/bin/csexec
using System;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello Console");
Console.WriteLine("Arguments: " + string.Join(", ", args));
}
}
请注意,命令行参数被传递给 C# 脚本,但 shebang 参数(在上面的第一个 C# 脚本中“-r:System.Windows.Forms.dll -r:System.Drawing.dll”)被传递到 C# 编译器。使用后一种功能,您可以在 C# 脚本的第一行指定所需的任何编译器参数。
如果您对 bash 脚本的工作原理感兴趣,shebang (#!) 将在 C# 脚本的第一行传递给它的所有参数集中在一起,然后是脚本名称,然后是传递的命令行参数到脚本本身。在上面的第一个 C# 示例中,以下 5 个参数将被传递到 bash 脚本中(用引号括起来):
"-r:System.Windows.Forms.dll -r:System.Drawing.dll" "hello.cs" "foo" "bar" "baz"
脚本确定第一个参数不是文件名,并假定它包含 C# 编译器的参数。然后它使用 'tail' 剥离 C# 脚本的第一行并将结果保存到临时文件(因为 C# 编译器不从标准输入读取)。最后,编译器的输出被保存到另一个临时文件,并使用传递给脚本的原始参数单声道执行。 'shift' 运算符用于消除编译器参数和脚本名称,只留下脚本参数。
执行 C# 脚本时,编译错误将转储到命令行。