【问题标题】:Collection of objects对象集合
【发布时间】:2012-10-10 07:40:16
【问题描述】:

我想在 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。

【问题讨论】:

    标签: collections x++ axapta dynamics-ax-2012


    【解决方案1】:

    最后一件事,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,这是作弊。

    另一方面,我没有看到您的请求的用例,即 Lists 应该包含任何类型。与设计目的背道而驰的是,一个 List 包含一个且仅一个在创建 List 对象时定义的类型。

    除了列表之外,还有other collections types,也许Struct 会满足您的需求。

    【讨论】:

    • 评论#1 在运行 job2 时遇到此异常... 执行代码时出错:转换函数的参数类型错误。堆栈跟踪 (C)\Jobs\Job2 - 第 6 行
    • @BilalSaeed - 注释掉“iVar = 1”,anytype 将绑定到一个字符串,而 any2str 将起作用。
    • 已删除 any2str,它不适用于绑定到 int 的 anytype
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多