如何读取匿名类型的属性?

编程入门 行业动态 更新时间:2024-10-15 04:22:56
本文介绍了如何读取匿名类型的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个返回的方法

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.

或者,只需使用反射.

更多推荐

如何读取匿名类型的属性?

本文发布于:2023-11-07 00:37:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1565076.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!