铸造匿名类型动态类型、动态

由网友(你、无法代替つ)分享简介:我有一个函数,返回,我想测试我的MVC控制器匿名类型。公共JsonResult富(){VAR数据=新{细节=东西,更多=更多};返回JSON(数据);}我想验证我从富函数获取数据,我现在做的是获得的数据类型,并得到它的属性值与反思。 [测试]公共无效TestOne(){VAR数据= _controller.Fo...

我有一个函数,返回,我想测试我的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(更多,更多);
}
 
详解C 匿名对象 匿名类型 var 动态类型 dynamic

解决方案

匿名对象是内部,这意味着他们的成员在声明这些组件外部受到很大限制。 动态尊重访问,所以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.

阅读全文

相关推荐

最新文章