Wiki

root/cobra/trunk/HowTo/301-ImplementIEnumerable2.cobra

Revision 2127, 1.2 KB (checked in by Chuck.Esterbrook, 3 years ago)

Take out is shared on def main in the how-to's.

  • Property svn:eol-style set to native
Line 
1"""
2ImplementIEnumerable2.cobra
3
4This version implements a generic file cabinet: You can give it any type of
5object to hold.
6
7
8See also: ImplementIEnumerable1.cobra
9"""
10
11
12class FileCabinet<of T> implements IEnumerable<of T>
13
14    get records from var = List<of T>()
15
16    get nextSerialNum as int
17        return _records.count + 1
18
19    def getEnumerator as IEnumerator<of T>
20        return _records.getEnumerator
21
22    def getEnumerator as System.Collections.IEnumerator
23        implements System.Collections.IEnumerable
24        return .getEnumerator
25
26
27class Record
28
29    cue init(serialNum as int, name as String)
30        base.init
31        _serialNum, _name = serialNum, name
32
33    pro serialNum from var as int
34
35    pro name from var as String
36
37    def toString as String is override
38        return '[.typeOf.name]([_serialNum], [_name])'
39
40
41class Program
42
43    def main
44        # build a cabinet:
45        cabinet = FileCabinet<of Record>()
46        cabinet.records.add(Record(cabinet.nextSerialNum, 'Red'))
47        cabinet.records.add(Record(cabinet.nextSerialNum, 'Green'))
48        cabinet.records.add(Record(cabinet.nextSerialNum, 'Blue'))
49
50        # because cabinet is an IEnumerable, it can be for'ed:
51        for r2 in cabinet, print r2
52
53        # and passed to a List initializer:
54        records = List<of Record>(cabinet)
55        for r3 in records
56            assert r3.serialNum > 0
Note: See TracBrowser for help on using the browser.