2012-10-10 177 views
4

我想在X ++中存储对象列表。我读过msdn中的数组和容器不能存储对象,所以唯一的选择是创建一个Collection的列表。我写了下面的代码,并尝试使用Collection = new List(Types::AnyType);Collection = new List(Types::Classes);,但两者都不起作用。请看看我是否在以下工作中犯了一些错误。对象集合

static void TestList(Args _args) 
{ 
    List Collection; 
    ListIterator iter; 
    anytype iVar, sVar, oVar; 

    PlmSizeRange PlmSizeRange; 
    ; 
    Collection = new List(Types::AnyType); 

    iVar = 1; 
    sVar = "abc"; 
    oVar = PlmSizeRange; 
    Collection.addEnd(iVar); 
    Collection.addEnd(sVar); 
    Collection.addEnd(oVar);  

    iter = new ListIterator(Collection); 
    while (iter.more()) 
    { 
     info(any2str(iter.value())); 
     iter.next(); 
    } 
} 

此外,我们不能将一些变量或对象转换为Anytype变量,我读出类型转换自动完成这种方式;

anytype iVar; 
iVar = 1; 

但是在运行时抛出一个错误,期望类型是Anytype,但是遇到的类型是int。第一

回答

6

末的事情,anytype变量需要首先分配给它的类型,你以后不能更改:

static void Job2(Args _args) 
{ 
    anytype iVar; 
    iVar = 1;    //Works, iVar is now an int! 
    iVar = "abc";   //Does not work, as iVar is now bound to int, assigns 0 
    info(iVar); 
} 

回到第一个问题,new List(Types::AnyType)行不通的addEnd方法测试的类型,其参数在运行时,并且anytype变量将具有分配给它的值的类型。

new List(Types::Object)将只存储对象,而不是简单的数据类型为intstr。 这可能与你(和C#)相信的相反,但简单的类型不是对象。

还剩什么?集装箱:

static void TestList(Args _args) 
{ 
    List collection = new List(Types::Container); 
    ListIterator iter; 
    int iVar; 
    str sVar; 
    Object oVar; 
    container c; 
    ; 
    iVar = 1; 
    sVar = "abc"; 
    oVar = new Object(); 
    collection.addEnd([iVar]); 
    collection.addEnd([sVar]); 
    collection.addEnd([oVar.toString()]); 
    iter = new ListIterator(collection); 
    while (iter.more()) 
    { 
     c = iter.value(); 
     info(conPeek(c,1)); 
     iter.next(); 
    } 
} 

对象不会自动转化为容器,通常你提供packunpack方法(实现接口SysPackable)。在上面的代码中使用toString这是作弊。

在另一方面,我没有看到你的要求的使用情况,列出应该包含任何类型的。违反其设计目的,列表包含创建List对象时定义的唯一一种类型。

除了列表有other collections types,也许Struct将满足您的需求。

+0

评论#1 运行job2时得到此异常... 执行代码时出错:转换函数的参数类型错误。 堆栈跟踪 (C)\作业\作业2 - 线6 –

+0

@BilalSaeed - 评出“的Ivar = 1”,并且将anytype类型被绑定到一个串和any2str将工作。 –

+1

删除'any2str',它不适用于绑定到int的'anytype'! –