我有一个想要的课程IList<T>,但我有一个Systems.Collection.IList来自NHibernate的人.
我想创建一个将其转换为的方法IList<T>.我该怎么做呢?
Tam*_*ege 76
如果您确定所有元素都继承自T(或您正在使用的任何类型)
IList<T> myList = nonGenericList.Cast<T>().ToList();
Run Code Online (Sandbox Code Playgroud)
如果您不确定:
IList<T> myList = nonGenericList.OfType<T>().ToList();
Run Code Online (Sandbox Code Playgroud)
当然,您将需要System.Linq命名空间:
using System.Linq;
Run Code Online (Sandbox Code Playgroud)
Cast并OfType返回IEnumerable<T>实现,而不是IList<T>实现,因此它们对您没用.
打电话.Cast<T>().ToList将导致列表的额外副本,这可能会对性能产生负面影响.
更好的(恕我直言)方法是创建一个包装类并在运行中进行转换.你想要这样的东西:
class ListWrapper<T> : IList<T>
{
private IList m_wrapped;
//implement all the IList<T> methods ontop of m_wrapped, doing casts
//or throwing not supported exceptions where appropriate.
//You can implement 'GetEnumerator()' using iterators. See the docs for
//yield return for details
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处是不会创建整个列表的另一个副本.