在 Visual Studio 中测试简单的 C# 代码表达式

Test simple c# code expressions in Visual Studio

我想知道如何测试简单的 C# 表达式

1) 在 Visual Studio 和
中 2) 不在调试中,在设计模式中

说,我想验证return这段代码

?DateTime.ParseExact("2016", "yyyy")

int i;
int.TryParse("x55", out i);
?i

我立即 window 收到以下消息:

?DateTime.ParseExact("2016", "yyyy") 
The expression cannot be evaluated while in design mode.

Interactive Window(不要与 立即 window 混淆)将实现您正在寻找的东西。

它可以被View > Other Windows > C# Interactive访问,本质上是一个交互式编译器会话,运行独立于项目是否正在执行,允许您任意执行代码而无需构建并 运行 你的项目。

这是一个示例,说明可以在此 window

中执行的操作
> Random gen = new Random();
> DateTime RandomDay()
. {
.     int monthsBack = 1;
.     int monthsForward = 3;
.     DateTime startDate = DateTime.Now.AddMonths(-monthsBack);
.     DateTime endDate = DateTime.Now.AddMonths(monthsForward);    
.     int range = (endDate - startDate).Days;
.     return startDate.AddDays(gen.Next(range));
. }
> RandomDay()
[28/01/2020 15:11:51]

并且还使用外部 dll

> Newtonsoft.Json.Linq.JObject.Parse("{'myArticle': { 'myDate': '2020-03-24T00:00:00'}  }")
(1,1): error CS0103: The name 'Newtonsoft' does not exist in the current context

> #r "C:\Users\MyUser\.nuget\packages\newtonsoft.json.0.2\lib\netstandard2.0\Newtonsoft.Json.dll"

> Newtonsoft.Json.Linq.JObject.Parse("{'myArticle': { 'myDate': '2020-03-24T00:00:00'}  }")
JObject(1) { JProperty(1) { JObject(3) { JProperty(1) { [24/03/2020 00:00:00] } } } }

立即 window 在设计模式下不起作用。您需要使用构建在 Roslyn 之上的 "C# interactive window",因此安装 Roslyn 然后按照下面的 Wiki

https://github.com/dotnet/roslyn/wiki/Interactive-Window

C# Interactive window 通过以下菜单路径打开:

视图 > 其他 Windows > C# 交互

我已经在 Visual Studio 2019 年解决了你的问题,

  1. 首先我使用 nuget 包管理器安装 Microsoft.AspNetCore.Mvc.Newtonsoft.json。

  2. 第二次使用在静态非泛型中定义的此方法class 转储任何要验证的表达式。

      public static void DumpObject(this object value)    
      {
    
       Console.WriteLine(JsonConvert.SerializeObject(value, Formatting.Indented));  
    
      }
    

N.B:记得加上using Newtonsoft.Json;

  1. 最终形成 Main 方法调用 Class.YourDumpMethod(AnyObjToVerify); 如下:

    static void Main()
    
    {
    
     DateTime dt = DateTime.ParseExact("2016","yyyy", null, DateTimeStyles.None);
    
     Dump.DumpObject(dt);
    
     int i;
    
     bool b = int.TryParse("55", out i);
    
     Dump.DumpObject(i);
    
    }
    

希望对您有所帮助

您可以为此使用外部应用程序,例如 LINQPad:

或者Try .NET中的Jupyter笔记本: