我想在 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。
最佳答案
最后一件事,anytype
variables 采用首先分配给它的类型,以后不能更改它:
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)
只会存储对象,而不是像 int
这样的简单数据类型和 str
.这可能与您(和 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();
}
}
对象不会自动转换为容器,通常您提供
pack
和 unpack
方法(实现接口(interface) SysPackable
)。上述代码中toString
被使用,这是作弊。另一方面,我没有看到您的请求的用例,即 Lists 应该包含任何类型。它违背了它的设计目的,一个 List 只包含一种类型,正如 List 时所定义的那样。对象被创建。
除了列表还有other collections types ,也许是 Struct将满足您的需求。
关于collections - 对象的集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12814352/