Using dynamic in C# to access field of anonymous type - possible?

早过忘川 提交于 2019-12-23 10:16:14

问题


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:


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.



来源:https://stackoverflow.com/questions/6111175/using-dynamic-in-c-sharp-to-access-field-of-anonymous-type-possible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!