CollectionExtensionsCastToListTFrom, TTo Method

将一个强类型列表强制转换为另一个类型的强类型列表。

Definition

Namespace: QuickAdmin.Utils.Extensions.CollectionExtension
Assembly: QuickAdmin.Net (in QuickAdmin.Net.dll) Version: 1.2.1
C#
public static IList<TTo> CastToList<TFrom, TTo>(
	this IList<TFrom> list
)

Parameters

list  IListTFrom
要转换的列表。

Type Parameters

TFrom
转换前的元素类型。
TTo
转换后的元素类型。

Return Value

IListTTo
转换后的强类型列表。

Remarks

注意元素类型将被从 TFrom 强制转换为 TTo,且不会做任何类型检查操作。

Example

C#
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);
}

See Also