Cast an IList to an IList<t> using dynamic instantiation

会有一股神秘感。 提交于 2019-12-25 12:04:41

问题


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:-

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

I know that I can return

IList results = Sesssion.CreateQuery(...

but my service layers expect an

IList<AllName>

How can I achieve this?


回答1:


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.

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>());

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

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

EDIT: 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).



来源:https://stackoverflow.com/questions/1977295/cast-an-ilist-to-an-ilistt-using-dynamic-instantiation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!