繁体   English   中英

如何使用泛型和反射来复制列表的子集

[英]How to copy a subset of a list using generics and reflection

我需要将一个项目的子集从一个列表复制到另一个。 但是,我不知道列表中包含哪种项目-即使所传递的对象是列表。

我可以通过以下代码查看对象是否为列表

t = DataSource.GetType();

if (t.IsGenericType)
{
    Type elementType = t.GetGenericArguments()[0];
}

我看不到的是如何到达列表中的单个对象,因此可以将所需的对象复制到新列表中。

大多数列表类型实现非通用的System.Collections.IList

IList sourceList = myDataSource as IList;
if (sourceList != null)
{
    myTargetList.Add((TargetType)sourceList[0]);
}

您也可以using System.Linq; 并执行以下操作:

IEnumerable sourceList = myDataSource as IEnumerable;
if (sourceList != null)
{
    IEnumerable<TargetType> castList = sourceList.Cast<TargetType>();
    // or if it can't be cast so easily:
    IEnumerable<TargetType> convertedList =
        sourceList.Cast<object>().Select(obj => someConvertFunc(obj));

    myTargetList.Add(castList.GetSomeStuff(...));
}

您编写的代码不会告诉您类型是否为列表。
您可以做的是:

IList list = DataSource as IList;
if (list != null)
{
  //your code here....
}

这将告诉您数据源是否实现IList接口。
另一种方法是:

    t = DataSource.GetType();

    if (t.IsGenericType)
    {
        Type elementType = t.GetGenericArguments()[0];
        if (t.ToString() == string.Format("System.Collections.Generic.List`1[{0}]", elementType))
        {
              //your code here
        }
    }

((IList) DataSource)[i]如果实际上是列表,则将从列表中获取第i个元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM