铸造一个对象的IEnumerable< T>其中T是未知 [英] Casting an object to IEnumerable<T> where T is not known

查看:97
本文介绍了铸造一个对象的IEnumerable< T>其中T是未知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想与反思玩,碰到了以下情况。



在下面的代码,让我们假设'OBJ'可以是类型的IEnumerable<的;>或ICollection的<>或IList的<>。



我想这System.Object的强制转换为IEnumerable的<>总是(如ICollection的<>和IList的<>自IEnumerable<继承;>无论如何),这样我就喜欢枚举的收集和使用反射来写的单个项目。



这背后的动机是,我只是想看看怎么会串行器,在一般情况下,序列化数据所以我试图模仿,希望这种情况理解的反思了。



我想铸造对象的非通用的IEnumerable ,但认为这将导致对象的不必要的拳击,当我们说的IEnumerable<的实际情况; INT> ...我在想右

 私人无效WriteGenericCollection(obj对象)
{
型innerType = obj.GetType()GetGenericArguments()[0]。

//例子:IEnumerable的< INT>或IEnumerable的<客户>
型generatedType = typeof运算(IEnumerable的<>)MakeGenericType(innerType)。

//我怎么能枚举个别项目?
}


解决方案

好吧,既然你不知道实际类型的项目,直到运行时,你并不需要使用普通的的IEnumerable< T> 界面;只需使用非泛型之一,的IEnumerable (一般一个来自继承):

 私人无效WriteGenericCollection(obj对象)
{
的IEnumerable枚举=(IEnumerable的)目标文件;
的foreach(在枚举对象的项目)
{

}
}


I am trying to play with Reflection and ran into the following situation.

In the following code, let's assume that the 'obj' can be of types IEnumerable<> or ICollection<> or IList<>.

I would like to cast this System.Object to IEnumerable<> always (as ICollection<> and IList<> inherit from IEnumerable<> anyway), so that i would like to enumerate over the collection and use reflection to write the individual items.

Motivation behind this is I am just trying to see if how would Serializers, in general, serialize data and so I am trying to simulate that situation in the hope to understand Reflection too.

I thought of casting the object to non-generic IEnumerable, but thought that this would cause unnecessary boxing of objects, when let's say the actual instance of IEnumerable<int>...am I thinking right?

private void WriteGenericCollection(object obj)
    {
        Type innerType = obj.GetType().GetGenericArguments()[0];

        //Example: IEnumerable<int> or IEnumerable<Customer>
        Type generatedType = typeof(IEnumerable<>).MakeGenericType(innerType);

        //how could i enumerate over the individual items?
    }

解决方案

Well, since you don't know the actual type of the items until runtime, you don't need to use the generic IEnumerable<T> interface; just use the non-generic one, IEnumerable (the generic one inherits from it):

private void WriteGenericCollection(object obj)
{
    IEnumerable enumerable = (IEnumerable)obj;
    foreach(object item in enumerable)
    {
        ...
    }
}

这篇关于铸造一个对象的IEnumerable&LT; T&GT;其中T是未知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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