Line | |
---|
1 | using System;
|
---|
2 | using System.Collections;
|
---|
3 | using HeuristicLab.Persistence.Interfaces;
|
---|
4 |
|
---|
5 | namespace HeuristicLab.Persistence.Default.Decomposers {
|
---|
6 |
|
---|
7 | public class ArrayDecomposer : IDecomposer {
|
---|
8 |
|
---|
9 | public bool CanDecompose(Type type) {
|
---|
10 | return type.IsArray || type == typeof(Array);
|
---|
11 | }
|
---|
12 |
|
---|
13 | public IEnumerable DeCompose(object array) {
|
---|
14 | Array a = (Array)array;
|
---|
15 | yield return a.Rank;
|
---|
16 | for (int i = 0; i < a.Rank; i++) {
|
---|
17 | yield return a.GetLength(i);
|
---|
18 | }
|
---|
19 | foreach (object o in (Array)array) {
|
---|
20 | yield return o;
|
---|
21 | }
|
---|
22 | }
|
---|
23 |
|
---|
24 | public object Compose(IEnumerable elements, Type t) {
|
---|
25 | IEnumerator e = elements.GetEnumerator();
|
---|
26 | e.MoveNext();
|
---|
27 | int rank = (int)e.Current;
|
---|
28 | int[] lengths = new int[rank];
|
---|
29 | for (int i = 0; i < rank; i++) {
|
---|
30 | e.MoveNext();
|
---|
31 | lengths[i] = (int)e.Current;
|
---|
32 | }
|
---|
33 | Array a = Array.CreateInstance(t.GetElementType(), lengths);
|
---|
34 | int[] positions = new int[rank];
|
---|
35 | while (e.MoveNext()) {
|
---|
36 | a.SetValue(e.Current, positions);
|
---|
37 | positions[0] += 1;
|
---|
38 | for (int i = 0; i < rank-1; i++) {
|
---|
39 | if (positions[i] >= lengths[i]) {
|
---|
40 | positions[i] = 0;
|
---|
41 | positions[i + 1] += 1;
|
---|
42 | } else {
|
---|
43 | break;
|
---|
44 | }
|
---|
45 | }
|
---|
46 | }
|
---|
47 | return a;
|
---|
48 | }
|
---|
49 | }
|
---|
50 |
|
---|
51 | }
|
---|
Note: See
TracBrowser
for help on using the repository browser.