[英]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.