CollectionExtensionsCastToListTFrom, TTo Method
将一个强类型列表强制转换为另一个类型的强类型列表。
注意元素类型将被从 TFrom 强制转换为 TTo,且不会做任何类型检查操作。
public interface IFoo { }
public class ClassA : IFoo { }
public class ClassB : IFoo { }
// 某公共方法输入参数为父接口(或父类)列表:
public void FooCommonMethod(IList<IFoo> list) { }
// 当需要为子类列表调用该公共方法时:
public void Test()
{
var listA = new List<ClassA>();
var listB = new List<ClassB>();
// 这样是不行的:
// FooCommonMethod(listA);
// FooCommonMethod(listB);
// 转换后调用该公共方法:
IList<IFoo> castedListA = listA.CastToList<ClassA, IFoo>();
IList<IFoo> castedListB = listB.CastToList<ClassB, IFoo>();
FooCommonMethod(listA);
FooCommonMethod(listB);
}