SafelyCastedListTFrom, TTo Class
表示安全转换后的强类型列表。
Namespace: QuickAdmin.UtilsAssembly: QuickAdmin.Net (in QuickAdmin.Net.dll) Version: 1.1.6
public class SafelyCastedList<TFrom, TTo> : IList<TTo>,
ICollection<TTo>, IEnumerable<TTo>, IEnumerable
where TFrom : TTo
- Inheritance
- object SafelyCastedListTFrom, TTo
- Implements
- ICollectionTTo, IEnumerableTTo, IListTTo, IEnumerable
Type Parameters
- TFrom
- 转换前的元素类型。
- TTo
- 转换后的元素类型。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);
// 使用 SafelyCastedList:
IList<IFoo> castedListA = new SafelyCastedList<ClassA, IFoo>(listA);
IList<IFoo> castedListB = new SafelyCastedList<ClassB, IFoo>(listB);
FooCommonMethod(listA);
FooCommonMethod(listB);
// 也可使用本类库提供的扩展方法 IList<T>.CastToListSafely() 获取转换后的列表,然后调用该公共方法:
castedListA = listA.CastToListSafely<ClassA, IFoo>();
castedListB = listB.CastToListSafely<ClassB, IFoo>();
FooCommonMethod(listA);
FooCommonMethod(listB);
}