将IList转换为IList< t>使用动态实例化 [英] Cast an IList to an IList<t> using dynamic instantiation

查看:283
本文介绍了将IList转换为IList< t>使用动态实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用dyanmic实例化将以下NHibernate查询转换为IList< t>而不是IList。

I am try to convert the following NHibernate query using dyanmic instantiation into an IList<t> rather than an IList.

IList<AllName> allNames =
  (IList<AllName>)Session.CreateQuery(
  @"select new AllName(
  name.NameId, name.FirstName, origin.OriginId, origin.Description,
  name.Sex, name.Description, name.SoundEx
  ) from Name name join name.Origin origin")
  .SetFirstResult(skip)
  .SetMaxResults(pageSize);

运行这个我得到以下错误: -

Running this I get the following error:-


无法转换类型为
的对象'NHibernate.Impl.QueryImpl'以键入
'System.Collections.Generic.IList`1 [Domain.Model.Entities。 AllName]'。

Unable to cast object of type 'NHibernate.Impl.QueryImpl' to type 'System.Collections.Generic.IList`1[Domain.Model.Entities.AllName]'.

我知道我可以返回

IList results = Sesssion.CreateQuery(...

预期

IList<AllName>

如何实现这一点?

推荐答案

一个选择是写一个 IList< T> 实现代理到 IList ,在适当的地方进行转换,不应该太难, LINQ将使实现 IEnumerable< T> 等方面稍微简单一些 - 你可以调用底层迭代器并调用 Cast< T& ()

One option would be to write an IList<T> implementation which proxies to an IList, casting where appropriate. It shouldn't be too hard to do, albeit somewhat tedious. LINQ will make this slightly easier in terms of implementing IEnumerable<T> etc - you can just call the underlying iterator and call Cast<T>() on it, for example.

另一个解决方案是创建一个新的 List< T& code>从返回的列表:

Another solution would be to create a new List<T> from the returned list:

IList query = Session.CreateQuery(...);
IList<AllName> allNames = new List<AllName>(query.Cast<AllName>());

编辑:正如Sander所说,这是 ToList 用于:

As Sander so rightly points out, this is what ToList is for:

IList query = Session.CreateQuery(...);
return query.Cast<AllName>().ToList();

编辑:所有这一切都是NHibernate不可知的,因为它是 - 我实际上不知道关于NHibernate。 Rippo现在找到了一个更简单的答案 - List< AllName> (这是一个NHibernate方法)。

All of this has been NHibernate-agnostic, as it were - I don't actually know much about NHibernate. Rippo has now found a much simpler answer - call List<AllName> instead (which is an NHibernate method).

这篇关于将IList转换为IList&lt; t&gt;使用动态实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆