是否可以像 Immediate 那样在 C# Interactive (REPL) 中自动输出值?

Is it possible to automatically output value in C# Interactive (REPL) like Immediate does?

我开始使用 C# Interactive 并喜欢这样一个事实,即我可以像使用 Immediate 一样浏览和探索一些 API 功能,而无需 运行 和调试我的程序。

问题是它不会像 Immediate 那样输出信息,除非我使用变量名执行命令:

 > string.Format("{0,15}", 10m);         //hit enter, here there is no output
 > var a = string.Format("{0,15}", 10m); //hit enter so...
 > a                                     // hit enter and...
  "        10"                           //...here the value is shown
 >

有没有办法让 C# InteractiveImmediate 那样在每次评估中输出值(并且不需要像 Console.Write 那样编写更多代码)?

是的,要输出计算表达式的结果,只需不要在末尾放置分号。在你的例子中,而不是这个:

string.Format("{0,15}", 10m);

这样做:

string.Format("{0,15}", 10m)

See the documentation

当您以 语句(例如以 ; 结尾)结束时,您在声明变量时必须这样做,但您不会像预期的那样获得任何输出只有副作用。

当您以 表达式 结束时(例如,不以 ; 结束),您将获得该表达式的结果。解决方法是:

var a = string.Format("{0,15}", 10m); a

注意 a 作为最后的表达式,您将打印它的值。


就个人而言,对于我要测试的多行代码片段,我通常有一个 res 变量:

object res;
// code where I set res = something;
using (var reader = new System.IO.StringReader("test"))
{
    res = reader.ReadToEnd();
}
res

每次 Visual Studio 会话都会出现一次打字开销,但后来我只使用 Alt+ 到 select 之前的条目之一。

我知道这为时已晚,但任何正在寻找类似问题答案的人。如果您想 运行 一个 for 循环并在 C# 交互式 window 中打印值,您可以使用 Print() 方法:

string Characters = "Hello World!";
> foreach (char _Char in Characters)
. {
.     Print(_Char);
. }
'H'
'e'
'l'
'l'
'o'
' '
'W'
'o'
'r'
'l'
'd'
'!'