通过检查表达式树,我可以获得常量,实例字段和属性的值,但不能获取方法中定义的局部变量.
执行以下操作将输出1,2,3(来自常量,实例字段和属性)然后是异常,因为我不知道如何获取声明FieldInfo的实例以便为本地调用GetValue()变量.
using System;
using System.Linq.Expressions;
using System.Reflection;
namespace Example
{
class Program
{
private int _intField = 2;
static void Main()
{
new Program().Run();
Console.ReadLine();
}
private void Run()
{
IntProp = 3;
var intVariable = 4;
Test(() => 1);
Test(() => _intField);
Test(() => IntProp);
Test(() => intVariable);
}
public int IntProp { get; set; }
void Test<T>(Expression<Func<T>> func)
{
var body = func.Body;
if (body.NodeType == ExpressionType.Constant)
{
Console.WriteLine(((ConstantExpression)body).Value);
}
else
{
var memberExpression = body as …Run Code Online (Sandbox Code Playgroud) 我有一个基本的.net核心api网络应用程序和一个使用TestServer发出http请求的单元测试项目。
我有一个TestStartup类,该类将api项目中的Startup类子类化。
如果Startup类在单元测试项目中,则得到404响应。如果将TestStartup类移至api项目,则会收到200条响应。
Api项目
蜜蜂
<PackageReference Include="Microsoft.AspNetCore.App" />
Run Code Online (Sandbox Code Playgroud)
Program.cs
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
Run Code Online (Sandbox Code Playgroud)
启动文件
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvcCore();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
}
}
Run Code Online (Sandbox Code Playgroud)
TestController.cs
public class TestController : ControllerBase
{
[HttpGet("test")]
public ObjectResult Get()
{
return Ok("data");
}
}
Run Code Online (Sandbox Code Playgroud)
单元测试项目
Tests.csproj
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="2.1.2" />
<PackageReference Include="Microsoft.AspNetCore.TestHost" …Run Code Online (Sandbox Code Playgroud) integration-testing unit-testing asp.net-core asp.net-core-2.1