如何读取匿名类型的属性? [英] How to read a property of an anonymous type?

查看:92
本文介绍了如何读取匿名类型的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回的方法

return new  System.Web.Mvc.JsonResult()
{                     
    Data = new
    {
        Status = "OK", 
    }
}

我需要编写一个单元测试,以验证jsonResult.Data.status= "OK".

I need to write a unit test where I need to verify that jsonResult.Data.status= "OK".

如何读取状态属性?

更新: 我尝试了[assembly:InternalsVisibleTo("TestingAssemblyName")],但这没有帮助.我一直收到错误{'System.Web.Mvc.JsonResult'不包含'状态'的定义}

Update: I tried the [assembly: InternalsVisibleTo("TestingAssemblyName")], but that didn't help. I kept getting the error {"'System.Web.Mvc.JsonResult' does not contain a definition for 'Status'"}

此外,我认为我宁愿不修改正在测试的代码.

Besides I think I will prefer not modifying the code that I am testing.

因此,我接受了乔恩的建议,并进行了反思.

So I took Jon's advice and used reflection.

        var type = jsonResult.Data.GetType();

        var pinfo = type.GetProperty("Status");

        string  statusValue = pinfo.GetValue(jsonResult.Data,null).ToString();

        Assert.AreEqual("OK", statusValue);

推荐答案

最简单的方法可能是使用动态类型:

The simplest approach would probably be to use dynamic typing:

dynamic foo = ret.Data;
Assert.AreEqual("OK", foo.status);

请注意,您将需要使用[InternalsVisibleTo]来使单元测试程序集对生产程序集中的匿名类型具有访问权限,因为匿名类型将通过internal访问权限生成.

Note that you'll need to use [InternalsVisibleTo] in order to give your unit test assembly access to the anonymous type in your production assembly, as it will be generated with internal access.

或者,只需使用反射.

这篇关于如何读取匿名类型的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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