Collection of objects

I want to save a list of objects in X ++. I read in msdn that arrays and containers cannot store objects, so the only option is to make a Collection list. I wrote the following code and tried to use Collection = new List(Types::AnyType); and Collection = new List(Types::Classes); but both of them do not work. See if I'm wrong in the next assignment.

 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(); } } 

In addition, if we could not insert any variable or object into the Anytype variable, I read that type conversion is performed automatically in this way;

 anytype iVar; iVar = 1; 

But at startup, it throws an error, the expected type of which was Anytype, but the type encountered was int.

+4
source share
1 answer

First of all, anytype variables accept the type assigned to it first, you cannot change it later:

 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); } 

Returning to the first question, new List(Types::AnyType) will never work, since the addEnd method checks the type of its argument at run time, and anytype variables will have the type of the value assigned to it.

Also new List(Types::Object) will store objects, not simple data types like int and str . This may contradict your opinion (and C #), but simple types are not objects.

What is left? Containers:

 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(); } } 

Objects are not automatically converted to containers, usually you provide the pack and unpack methods (implementing the SysPackable interface). The code above uses toString , which is cheating.

On the other hand, I see no use case for your request that lists should contain any type. This contradicts its purpose; the list contains one and only one type defined when creating the List object.

In addition to lists, there are other types of collections , perhaps Struct will suit your needs.

+6
source

Source: https://habr.com/ru/post/1438828/


All Articles