代码之家  ›  专栏  ›  技术社区  ›  Paul S Chapman

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

  •  1
  • Paul S Chapman  · 技术社区  · 14 年前

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

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

    我看不到的是如何获取列表中的各个对象,以便将所需对象复制到新列表中。

    3 回复  |  直到 14 年前
        1
  •  1
  •   Itay Karo    14 年前

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

    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
            }
        }
    
        2
  •  2
  •   herzmeister    14 年前

    大多数列表类型实现非泛型 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(...));
    }
    
        3
  •  0
  •   recursive    14 年前

    ((IList) DataSource)[i] 会得到 i