![](/img/trans.png)
[英]Why can't I access properties of an anonymous type returned from a function via the dynamic keyword?
[英]Uniting JsonResult why can't I get access through dynamic if the items are an anonymous type
我有一個方法看起來像:
public JsonResult GetSpecies()
{
var species = new List<SpeciesType> {
new SpeciesType{ Id=1, Name="Giraffe" },
new SpeciesType{ Id=2, Name="Wolf" }
};
return Json(new { Species = species });
}
然后我進行了組裝,使其內部可見我的測試項目並進行了測試:
[TestMethod]
public void GetSpecies_ReturnsJsonVersionOfNameAndId()
{
...
var result = controller.GetSpecies();
dynamic data = result.Data;
Assert.AreEqual(1, data.Species[0].Id);
Assert.AreEqual("Giraffe", data.Species[0].Name);
Assert.AreEqual(2, data.Species[1].Id);
Assert.AreEqual("Wolf", data.Species[1].Name);
}
所以這很好。
我改變了方法以返回數組中的匿名類型:
public JsonResult GetSpecies()
{
var species = new List<SpeciesType> {
new SpeciesType{ Id=1, Name="Giraffe" },
new SpeciesType{ Id=2, Name="Wolf" }
}.Select(x => new { Id = x.Id, Name = x.Name });
return Json(new { Species = species });
}
測試現在拋出異常。
任何人都可以解釋為什么會發生這種情況以及如何解決?
您現在沒有提供List<T>
- 您的Species
屬性只是一個序列。 我不知道它是如何在JSON中表示的,如果它實際上是通過線路,它可能沒問題 - 但是確保Species
值實際上是一個列表可能是最簡單的:
var species = new List<SpeciesType> {
new SpeciesType{ Id=1, Name="Giraffe" },
new SpeciesType{ Id=2, Name="Wolf" }
}
.Select(x => new { Id = x.Id, Name = x.Name })
.ToList();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.