使用C#中的动态访问匿名类型的领域 - 可能吗? [英] Using dynamic in C# to access field of anonymous type - possible?

查看:348
本文介绍了使用C#中的动态访问匿名类型的领域 - 可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制器的方法:

I've got a controller method:

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

现在,我想测试。

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

这将引发RuntimeBinderException说,计算没有定义。有什么办法来实现这一目标?

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

更新

继容斯的意见我用InternalsVisibleTo去亲近我的测试组件。一切工作正常。谢谢乔恩。

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.

还应如果你使用好起来的 InternalsVisibleTo 在生产装配授予访问权限你的测试组件,虽然。

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

这篇关于使用C#中的动态访问匿名类型的领域 - 可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆