简体   繁体   English

如何使用“动态”变量从匿名类型中读取属性

[英]How to read properties from anonymous types using “dynamic” variable

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 我有一个狡猾的想法,即使用动态变量来测试返回匿名类型的方法的结果 - 更具体地说,它返回一个JsonResult,就像json看起来像这样

{ "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. 我可以阅读JSonResult,它将给我匿名类型。 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? 但是我如何获得“newData”呢? 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. 给了我一个System.Linq.Enumerable.WhereSelectArrayIterator,但我不知道如何处理它才能将它用作双打结果。

I tried casting it as a double[], but it doesn't work either. 我尝试将它作为double []进行投射,但它也不起作用。

As an aside, can I easily check if a property is defined on the dynamic? 顺便说一句,我可以轻松检查动态上是否定义了属性?

The reason .ToArray() doesn't work is that it's an extension method, and extension methods aren't available at runtime. 原因.ToArray()不起作用的是它是一个扩展方法,并且扩展方法在运行时不可用。 That just means you have to call the function statically. 这只是意味着你必须静态调用该函数。 Does Enumerable.ToArray<double>(data.newData) work? Enumerable.ToArray<double>(data.newData)有效吗?

You may need Enumerable.ToArray(Enumerable.Cast<double>(data.newData)) depending on what elements newData actually has. 您可能需要Enumerable.ToArray(Enumerable.Cast<double>(data.newData))具体取决于newData实际具有的元素。

To get the properties of an instance of a dynamic type 获取动态类型实例的属性

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(dyn);
foreach (PropertyDescriptor prop in props)
{
  object val = prop.GetValue(dyn);
  var propName = prop.Name;
  var propValue = val;
}

where dyn is an instance of a dynamic object. 其中dyn是动态对象的实例。

Could you use the JavaScriptSerializer class to parse the Json string into a dynamic variable? 您可以使用JavaScriptSerializer类将Json字符串解析为动态变量吗? Eg: 例如:

var serializer = new JavaScriptSerializer();
var jsonObj = serializer.Deserialize<dynamic>(jsonString);
var newData1 = jsonObj["newData"][0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM