[英]Could not convert IEnumerable of anonymous type to IEnumerable<dynamic>?
我有一個在控制器中搜索人員的操作,它將返回匿名者列表:
[UnitOfWork]
[HttpGet, Route("api/Search/People")]
public virtual IHttpActionResult GetResult(string keyword)
{
// ...
var result = peopleList.Select(x => new
{
PersonId = x.Id.Value,
EmploymentNumber = x.EmploymentNumber,
FirstName = x.Name.FirstName,
LastName = x.Name.LastName,
Email = x.Email
});
return Ok(result);
}
下面是該方法的測試案例:
[Test]
public void ShouldSearchPeople()
{
// Mocks...
var target = new PeopleSearchController(searchRepository, personRepository, new FakePermissionProvider());
// Error here
var result = (OkNegotiatedContentResult<IEnumerable<dynamic>>)target.GetResult("Ashley");
Assert.NotNull(peopleList);
// Other assert...
}
然后我得到如下錯誤:
System.InvalidCastException: Unable to cast object of type
'System.Web.Http.Results.OkNegotiatedContentResult`1[System.Collections.Generic.IEnumerable`1[<>f__AnonymousType1e`5[System.String,System.String,System.String,System.Guid,System.String]]]'
to type
'System.Web.Http.Results.OkNegotiatedContentResult`1[System.Collections.Generic.IEnumerable`1[System.Object]]'.
看來IEnumerable與類或單個匿名對象可以進行此類轉換,但IEnumerable與匿名對象不起作用。
我該如何進行轉換? 謝謝。
您不是在將某些參數轉換為動態參數,而是將其參數化類型轉換為其他參數化類型。 您的代碼所遭受的問題稱為協方差和逆方差。 不幸的是, class
不支持協方差/ contravariance( class
始終是不變的)。 可能的解決方法:
var result = ((dynamic)target).GetResult("Ashley");
//result is of type OkNegotiatedContentResult<...>
var content = (IEnumerable<dynamic>)result.Content;
由於IEnumerable
是協變的,因此該轉換將起作用。
您可以嘗試
IHttpActionResult result = target.GetResult("Ashley");
IEnumerable<dynamic> content = (IEnumerable<dynamic>)((dynamic)result).Content;
您使用dynamic
來使用.Content
屬性,該屬性將返回IEnumerable<T>
,然后使用協方差將其.Content
為IEnumerable<object>
/ IEnumerable<dynamic>
(在CLR級別上,它們是等效的... dynamic
是一種魔力由編譯器完成)
請注意,如果OkNegotiatedContentResult
的T
為值類型,則此方法OkNegotiatedContentResult
,但在您的情況下,它為引用類型,因此沒有問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.