在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