Using dynamic in C# to access field of anonymous t

2019-06-21 19:12发布

I've got a controller method:

public JsonResult CalculateStuff(int coolArg)
{
    if(calculatePossible)
       return Json(CoolMethod(coolArg));
    else return Json(new { Calculated = false });
}

Now, I'd like to test this.

public void MyTest
{
    var controller = GetControllerInstance();
    var result = controller.CalculateStuff().Data as dynamic;
    Assert.IsTrue(result.Calculated == false);        
}

This throws a RuntimeBinderException saying that Calculated is not defined. Is there any way to achieve this?

UPDATE

Following Jons' advice, I used InternalsVisibleTo to befriend my test assembly. Everything works fine. Thank you Jon.

1条回答
看我几分像从前
2楼-- · 2019-06-21 19:38

You can do it, but only within the same assembly. The anonymous type is internal.

It should also be okay if you use InternalsVisibleTo in your production assembly to grant access to your test assembly though.

查看更多
登录 后发表回答