铸造匿名类型动态 [英] Casting anonymous type to dynamic

查看:235
本文介绍了铸造匿名类型动态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,返回,我想测试我的MVC控制器匿名类型。

 公共JsonResult富()
{
    VAR数据=新
                  {
                      细节=东西,
                      更多=更多
                  };
    返回JSON(数据);
}
 

我想验证我从富函数获取数据,我现在做的是获得的数据类型,并得到它的属性值与反思。

  [测试]
公共无效TestOne()
{
    VAR数据= _controller.Foo()数据。
    VAR细节= data.GetType()的getProperty(信息)的GetValue(数据,空)。
    VAR更多= data.GetType()的getProperty(更多)的GetValue(数据,空)。

    Assert.AreEquals(东西,详细说明);
    Assert.AreEquals(更多,更多);
}
 

有没有类似这样的一个简单的方法来检查匿名属性?

  [测试]
公共无效TestTwo()
{
    VAR数据=(动态)_controller.Foo()数据。
    VAR细节= data.details; // RunTimeBinderException对象不包含定义详细信息
    VAR更多= data.more;

    Assert.AreEquals(东西,详细说明);
    Assert.AreEquals(更多,更多);
}
 

解决方案

匿名对象是内部,这意味着他们的成员在声明这些组件外部受到很大限制。 动态尊重访问,所以pretends不能够看到这些成员。如果呼叫站点在同一程序集,我希望这是可行的。

您反映code尊重的成员的可访问性,但绕过类型的可访问性 - 因此它的工作原理

在短期:没有

I have a function that returns an anonymous type which I want to test in my MVC controller.

public JsonResult Foo()
{
    var data = new
                  {
                      details = "something",
                      more = "More"
                  };
    return Json(data);
}

I want to verify the data I get from the Foo function, What I'm doing now is getting the data type and get it's properties values with reflection.

[Test]
public void TestOne()
{
    var data = _controller.Foo().Data;
    var details = data.GetType().GetProperty("details").GetValue(data, null);
    var more = data.GetType().GetProperty("more").GetValue(data, null);

    Assert.AreEquals("something", details);
    Assert.AreEquals("More", more);
}

Is there a simple way similar to this to check the anonymous properties?

[Test]
public void TestTwo()
{
    var data = (dynamic) _controller.Foo().Data;
    var details = data.details; // RunTimeBinderException object does not contain definition for details
    var more = data.more;

    Assert.AreEquals("something", details);
    Assert.AreEquals("More", more);
}

解决方案

Anonymous objects are internal, which means their members are very restricted outside of the assembly that declares them. dynamic respects accessibility, so pretends not to be able to see those members. If the call-site was in the same assembly, I expect it would work.

Your reflection code respects the member accessibility, but bypasses the type's accessibility - hence it works.

In short: no.

这篇关于铸造匿名类型动态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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