开发者

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

开发者 https://www.devze.com 2023-03-07 21:06 出处:网络
I\'ve got a controller method: public JsonResult CalculateStuff(int coolArg) { if(calculatePossible) return Json(CoolMethod(coolArg));

I've got a controller method:

public JsonResult CalculateStuff(int coolArg)
{
    if(calculatePossible)
       return Json(CoolMethod(coolArg));
    else return Json(new { Calculated = false });
}
开发者_StackOverflow中文版

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号