我試圖從通用列表中獲取某個索引編號的項目編號,我得到:無法投射類型爲「System.Collections.Generic.List 1[typename]' to type 'System.Collections.Generic.List
1 [System 。目的]'。錯誤。從通用列表獲取索引項拋出錯誤
我想要實現的是循環(向前或向後)到基於繼承的基類的某個列表;像這樣(或類似的東西反正):
public class Fruit
{
public string Name {get;set;}
}
public class Apple : Fruit
{
public bool IsSour {get;set;}
}
public class Orange : Fruit
{
public bool Juicy {get;set;}
}
public List<Apple> Apples = new List<Apple>();
public List<Orange> Oranges = new List<Oranges>();
想什麼,我到是這樣的:
public string[] BuildList(object GenericListHere, bool Backwards)
{
for(int i=GenericListHere.Length-1;i>=0;i--)
{
string MyName = GenericListHere[i].Name;
上面有所pseudocoded,但我想要麼扔在蘋果或橙子名單得到結果。 我不事先知道哪一個對象我得到,所以我得到這樣的(未psuedocoded)計算/長度,其中TestObj就是我得到的對象:
int iBound = -1;
try
{
System.Reflection.PropertyInfo oInfo = TestObj.GetType().GetProperty("Count");
iBound = (int)oInfo.GetValue(TestObj, null);
}
catch
{
而且如果iBound> = 0這是一個集合。接下來的部分..我多少有些失落......
if (iBound != -1)
{
int iLoopStart = (backwardsLoop ? iBound - 1 : 0);
int iLoopEnd = (backwardsLoop ? -1 : iBound);
int iLoopDifference = (backwardsLoop ? -1 : +1);
for (int iLoop = iLoopStart; iLoop != iLoopEnd; iLoop += iLoopDifference)
{
// THIS IS REALLY BAD CODED.. BUT I DONT GET IT
object VarCollection = TestObj;
object[] arInt = new object[1];
arInt.SetValue(iLoop, 0);
Type[] tArray = new Type[1];
tArray.SetValue(typeof(int), 0);
object oElem = ((System.Collections.Generic.List<object>)VarCollection)[iLoop];
我真正喜歡的是一樣的東西:VarCollection [ILOOP],但是這似乎並沒有工作..
任何人有這些列表的經驗嗎? TIA!
仍然需要知道演員的正確類型。 – riffnl 2010-11-04 10:12:51
@riffnl:不,你不知道。或者請解釋你爲什麼會這麼想。 – leppie 2010-11-04 10:14:32
「因爲編譯器這麼說」我的答案肯定會是......但是使用System。集合似乎做了這個伎倆。 – riffnl 2010-11-04 10:17:09