从我在这里的问题:在List对象中转换
我使用LINQ接受了答案:
myA = myB.Cast<A>().ToList();
Run Code Online (Sandbox Code Playgroud)
我有一个问题:我们有任何其他解决方案而不使用LINQ,因为我的应用程序使用的是.NET Framework 2.0.
更新:
如果我有几个类myB,myC,myD,myE,...派生自myA,我需要一个可以将列表转换为列表的函数(T可能是myB或myC或myD,...)以避免重复相同的代码.The function input is a list<T> and the function output is a list<myA>.
谢谢.
一个简单的foreach
会做的伎俩(为了可读性,我已经命名了类Foo和Bar)
myFoos = new List<Foo>();
foreach (Bar bar in myBars)
{
myFoos.Add((Foo)bar);
}
Run Code Online (Sandbox Code Playgroud)
问题编辑后:
要将多个子类的列表转换为基类,我将创建一个名为BaseCollection的类,而不是从List继承的类,因为通常还需要列表中的一些其他操作.一些有用的方法可能是:
public class BaseCollection : List<Base>
{
public static BaseCollection ToBase<T>(IEnumerable<T> source) where T: Base
{
BaseCollection result = new BaseCollection();
foreach (T item in source)
{
result.Add(item);
}
return result;
}
public static List<T> FromBase<T>(IEnumerable<Base> source) where T: Base
{
List<T> result = new List<T>();
foreach (Base item in source)
{
result.Add((T)item);
}
return result;
}
public static List<T> ChangeType<T, U>(List<U> source) where T: Base where U:Base
{
List<T> result = new List<T>();
foreach (U item in source)
{
//some error checking implied here
result.Add((T)(Base) item);
}
return result;
}
....
// some default printing
public void Print(){...}
....
// type aware printing
public static void Print<T>(IEnumerable<T> source) where T:Base {....}
....
}
Run Code Online (Sandbox Code Playgroud)
这将使我能够轻松地将任何后代转换为基类集合,并使用它们,如下所示:
List<Child> children = new List<Child>();
children.Add(new Child { ID = 1, Name = "Tom" });
children.Add(new Child { ID = 2, Name = "Dick" });
children.Add(new Child { ID = 3, Name = "Harry" });
BaseCollection bases = BaseCollection.ToBase(children);
bases.Print();
List<Child> children2 = BaseCollection.FromBase<Child>(bases);
BaseCollection.Print(children2);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
728 次 |
最近记录: |