加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将对象转换为集合

发布时间:2020-12-16 01:53:11 所属栏目:百科 来源:网络整理
导读:我有一个情况,我得到一个对象,需要: 确定该对象是单个对象还是集合(数组,列表等) 如果是集合,请单击列表. 到目前为止我有什么. IEnumerable的测试不起作用.转换为IEnumerable仅适用于非基本类型. static bool IsIEnumT(T x){ return null != typeof(T).GetI
我有一个情况,我得到一个对象,需要:

>确定该对象是单个对象还是集合(数组,列表等)
>如果是集合,请单击列表.

到目前为止我有什么. IEnumerable的测试不起作用.转换为IEnumerable仅适用于非基本类型.

static bool IsIEnum<T>(T x)
{
    return null != typeof(T).GetInterface("IEnumerable`1");
}
static void print(object o)
{
    Console.WriteLine(IsIEnum(o));       // Always returns false
    var o2 = (IEnumerable<object>)o;     // Exception on arrays of primitives
    foreach(var i in o2) {
        Console.WriteLine(i);
    }
}
public void Test()
{
    //int [] x = new int[]{1,2,3,4,5,6,7,8,9};
    string [] x = new string[]{"Now","is","the","time..."};
    print(x);       
}

有人知道怎么做吗?

解决方法

检查对象是否可以转换为非通用IEnumerable接口就足够了:

var collection = o as IEnumerable;
if (collection != null)
{
    // It's enumerable...
    foreach (var item in collection)
    {
        // Static type of item is System.Object.
        // Runtime type of item can be anything.
        Console.WriteLine(item);
    }
}
else
{
    // It's not enumerable...
}

IEnumerable的< T>它本身实现IEnumerable,因此这将适用于泛型和非泛型类型.使用该接口而不是通用接口避免了通用接口方差的问题:IEnumerable< T>不一定可以转换为IEnumerable< object>.

这个问题更详细地讨论了通用接口方差:Generic Variance in C# 4.0

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读