方法返回List的动态类型

时间:2014-10-09 13:14:52

标签: c# list generics

如果我有以下内容:

class Super {
 //stuff 
}

class Sub1 : Super {
 //stuff
}

class Sub2 : Super {
 //stuff
}

class Sub3 : Super {
 //stuff
}

运行类

class Run {

 //list of type Super with a bunch of sub objects (sub1,sub2,sub3)
 List<Super> superList = sub1,2,3 list;
 List<Super> partialSuperList;

 void doStuff() {
  Type subObjectType = superList[0].GetType();
  if (subObjectType == typeof(sub1)) {
   partialSuperList = categorize(subObjectType);
  } else if (subObjectType == typeof(sub2)) {
   partialSuperList = categorize(subObjectType);
  } else if (subObjectType == typeof(sub3)) {
   partialSuperList = categorize(subObjectType);
  }
 }

 List<Super> categorize(Type type) {
  List<type> subTypeList = new List<type>();
  //loop through subtype list and add it to a super type list
  return SuperList;
 }
}

正如你所看到的,我正在尝试动态创建一个带有“type”的列表,该列表来自方法的参数,我这样做是对还是有其他方法可以做到这一点?

2 个答案:

答案 0 :(得分:3)

由于您的伪代码目前尚无法编译,因此很难判断您是否做了正确的事情。

我认为您正在尝试根据某种类型过滤列表。我认为Linq方法OfType<TResult>正是您所寻找的。

var superList = new List<Super> { ... };
var sub1List = superList.OfType<Sub1>().ToList();
var sub2List = superList.OfType<Sub2>().ToList();
var sub3List = superList.OfType<Sub3>().ToList();

如果您想要在编译时过滤您不知道的类型,可以执行以下操作:

var superList = new List<Super> { ... };
var someType = superList.First().GetType();
var filteredSuperList = superList.Where(x => x.GetType() == someType).ToList();

答案 1 :(得分:1)

使方法通用:

List<T> doStuff<T>() where T : Super
{
    List<T> list = new List<T>();

    // use list
}

您没有现在的投射问题,可以使用T检查is

if (T is Sub1)
{
    ... // do something
}