如何使用“动态”从匿名类型读取属性多变的
我有一个狡猾的想法,使用动态变量来测试返回匿名类型的方法的结果 - 更具体地说,它返回一个 JsonResult,因为 json 看起来像这样,所以
{ "newData" : [ 1120741.2697475906,
826527.64681837813
],
"oldData" : [ 1849870.2326665826,
1763440.5884212805
],
"timeSteps" : [ 0,
4.8828124999999998e-10
],
"total" : 2
}
我可以读取 JsonResult 它将给我匿名类型。这是我的代码:
var jsonResult = controller.GetChangeData(1) as JsonResult;
dynamic data = jsonResult.Data;
Assert.AreEqual(2, data.total); // This works fine :)
但是,例如,我如何获取“newData”?这段代码......
var newData = data.newData;
给了我一个 System.Linq.Enumerable.WhereSelectArrayIterator,但我不知道如何处理它才能将它用作双精度数组。
我尝试将其转换为 double[],但它也不起作用。
顺便说一句,我可以轻松检查动态中是否定义了属性吗?
I had the cunning idea of using a dynamic variable to test the results of a method that returns an anonymous type - more specifically it returns a JsonResult, which as json looks like this
{ "newData" : [ 1120741.2697475906,
826527.64681837813
],
"oldData" : [ 1849870.2326665826,
1763440.5884212805
],
"timeSteps" : [ 0,
4.8828124999999998e-10
],
"total" : 2
}
I can read the JSonResult which will give me the anonymous type. Here's my code:
var jsonResult = controller.GetChangeData(1) as JsonResult;
dynamic data = jsonResult.Data;
Assert.AreEqual(2, data.total); // This works fine :)
But how do I get at "newData" for example? This code....
var newData = data.newData;
Gives me a System.Linq.Enumerable.WhereSelectArrayIterator, but I don't know what to do with it to be able to just use it as an arry of doubles.
I tried casting it as a double[], but it doesn't work either.
As an aside, can I easily check if a property is defined on the dynamic?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
.ToArray()
不起作用的原因是它是一个扩展方法,并且扩展方法在运行时不可用。这仅意味着您必须静态调用该函数。Enumerable.ToArray(data.newData)
有效吗?您可能需要
Enumerable.ToArray(Enumerable.Cast(data.newData))
,具体取决于newData
实际拥有的元素。The reason
.ToArray()
doesn't work is that it's an extension method, and extension methods aren't available at runtime. That just means you have to call the function statically. DoesEnumerable.ToArray<double>(data.newData)
work?You may need
Enumerable.ToArray(Enumerable.Cast<double>(data.newData))
depending on what elementsnewData
actually has.获取动态类型实例的属性
,其中 dyn 是动态对象的实例。
To get the properties of an instance of a dynamic type
where dyn is an instance of a dynamic object.
您可以使用 JavaScriptSerializer 类将 Json 字符串解析为动态变量吗?例如:
Could you use the JavaScriptSerializer class to parse the Json string into a dynamic variable? Eg: