在C#中,我想在那里我知道“T”支持界面“IMyInterface的”,并采取“T”型数组:在C#中,如何将IEnumerable <IMyInterface>的数组转换为IEnumerable <T>?
- 将它转换为“IMyInterface的”
- 呼叫数组在该阵列上将过滤列表的方法
- 将其重新转换回原始类型T列表。
1和2上面的工作正常,但我遇到了步骤#3的问题。
这里是我的代码:
IEnumerable<IMyInterface> castedArray = originalTypedArray as IEnumerable<IMyInterface>;
if (castedArray != null)
{
var filteredArray = castedArray.Where(r => r.Ids.Contains(MyId)).ToList();
IEnumerable<T> castedBackToOriginalTypeArray = filteredArray as IEnumerable<T>;
if (castedBackToOriginalTypeArray == null)
{
current = new List<T>();
}
else
{
current = castedBackArray;
}
// I need to cast back, because only my Type T has the .Id property
List<int> ids = current.Select(r => r.Id).ToList();
}
的问题是在这条线:
IEnumerable<T> castedBackToOriginalTypeArray = filteredArray as IEnumerable<T>;
这似乎总是返回null(而不是滤波阵列转换回IEnumerable的< T>。
这里的任何建议,我可能会做错什么,以及如何正确地将一个接口数组转换回T型数组?
从'T'投射到'IMyInterface'是否工作在没有IEnumerable的情况下? – kat1330
你为什么需要演员?你不能过滤原始的'IEnumerable'吗? –
@LucMorin - 我在IEnumerable上做过滤器,但我需要将其转换回原来的类型,因为我的下一行代码依赖于它..我已更新问题以使其更清晰 –
leora