【发布时间】:2011-05-04 22:57:36
【问题描述】:
我正在尝试从通用列表中按编号获取某个索引项,但我得到:无法转换类型为“System.Collections.Generic.List1[typename]' to type 'System.Collections.Generic.List1[System.Object]”的对象。错误。
我想要实现的是基于继承的基类循环(向前或向后)到某个列表;像这样(或类似的东西):
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;
上面的代码有点伪代码,但我想输入苹果或橙子列表以获得结果。 我事先不知道我得到的是哪个对象,所以我得到了这样的计数/长度(不是伪编码),其中 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],但这似乎不起作用..
有人对这类列表有经验吗?蒂亚!
【问题讨论】:
标签: c# list collections generics