((IEnumerable)source).OfType<T>()
和source as IEnumerable<T>
之间有什么区别((IEnumerable)source).OfType <T>()和source为IEnumerable <T>之间的区别是什么?
对我来说它们看起来很相似,但它们不是!
source
的类型为IEnumerable<T>
,但它被装箱为object
。
编辑
这里是一些代码:
public class PagedList<T> : List<T>, IPagedList
{
public PagedList(object source, int index, int pageSize, int totalCount)
{
if (source == null)
throw new ArgumentNullException("The source is null!");
// as IEnumerable<T> gives me only null
IEnumerable<T> list = ((IEnumerable)source).OfType<T>();
if (list == null)
throw new ArgumentException(String.Format("The source is not of type {0}, the type is {1}", typeof(T).Name, source.GetType().Name));
PagerInfo = new PagerInfo
{
TotalCount = totalCount,
PageSize = pageSize,
PageIndex = index,
TotalPages = totalCount/pageSize
};
if (PagerInfo.TotalCount % pageSize > 0)
PagerInfo.TotalPages++;
AddRange(list);
}
public PagerInfo PagerInfo { get; set; }
}
在另一个地方我创建了一个PagedList的实例
public static object MapToPagedList<TSource, TDestination>(TSource model, int page, int pageSize, int totalCount) where TSource : IEnumerable
{
var viewModelDestinationType = typeof(TDestination);
var viewModelDestinationGenericType = viewModelDestinationType.GetGenericArguments().FirstOrDefault();
var mappedList = MapAndCreateSubList(model, viewModelDestinationGenericType);
Type listT = typeof(PagedList<>).MakeGenericType(new[] { viewModelDestinationGenericType });
object list = Activator.CreateInstance(listT, new[] { (object) mappedList, page, pageSize, totalCount });
return list;
}
如果有人能告诉我为什么我必须施放mappedList到object,我真的很感激:)
这里的MapAndCreateSubList方法和Map委托:
private static List<object> MapAndCreateSubList(IEnumerable model, Type destinationType)
{
return (from object obj in model select Map(obj, obj.GetType(), destinationType)).ToList();
}
public static Func<object, Type, Type, object> Map = (a, b, c) =>
{
throw new InvalidOperationException(
"The Mapping function must be set on the AutoMapperResult class");
};
这是一个测验问题?你好像忽略了一些信息。无论如何,OfType将enumerable过滤为只有这种类型的元素,所以这是最大的区别。 –
2010-09-17 21:53:36
我在我的代码源中使用IEnumerable,并证明它不是null,但它是空的。我看着调试器,我看到T是正确的。然后我使用((IEnumerable)源).OfType ()和铸造是正确的,没有空结果。如果你想我可以发布更多的代码。 –
Rookian
2010-09-17 21:56:21