2009-08-07 45 views
1

我试图使用CodeDom生成C#(.NET 2.0)代码,将执行以下操作:如何使用CodeDom初始化数组(或锯齿状数组)的数组?

int[][] myArray = new int[someSize][]; 

在CodeDom中,初始化数组的需要CodeArrayCreateExpression。 MSDN说:

如果语言允许数组数组,则可以通过在CodeArrayCreateExpression中嵌套CodeArrayCreateExpression来创建它们。

我的理解是,唯一的可能性就是写这样的:

// Declaration and initialization of myArray 
    CodeVariableDeclarationStatement variable = 
    new CodeVariableDeclarationStatement("System.Int32[][]", "myArray", 
     new CodeArrayCreateExpression("System.Int32[][]", 
     new CodeExpression[] { new CodeArrayCreateExpression("System.Int32[]", 0) })); 

但是这会产生这样的:

int[][] myArray = new int[][] { new int[0] }; 

这不是完美的,但我可以用它做如果我在世代时知道myArray的大小,我不知道。

我可以编写一个函数来完成初始化,并在CodeDom中调用它,但如果我可以在纯CodeDom中完成,它会更好。我错过了什么 ?

[编辑]背景信息

的想法是自动生成两个对象表示之间的适配器。我有一个元描述(某种IDL的)说:“我有具有int类型[] []的字段的容器对象”和该容器的两个表示:

// Internal representation 
public class InternalContainer { 
    int[][] myArray; 
} 

// Network representation 
public class NetworkContainer { 
    int[][] myArray; 
} 

因此问题生成可以适应任何大小数组的代码。

回答

-1
CodeArrayCreateExpression CodeArrayCreateExpression(Array array) 
    { 
    CodeArrayCreateExpression arrayCreateExpression = new CodeArrayCreateExpression(array.GetType(), array.GetLength(0)); 

    if (array.GetType().GetElementType().IsArray) 
    { 
     CodeArrayCreateExpression[] values = new CodeArrayCreateExpression[array.GetLength(0)]; 
     for (int j = 0; j < array.GetLength(0); j++) 
     { 
      values[j] = this.CodeArrayCreateExpression((Array)array.GetValue(j)); 
     } 

     arrayCreateExpression.Initializers.AddRange(values); 
    } 
    else if(array.GetType().GetElementType().IsPrimitive) 
    { 
     CodeCastExpression[] values = new CodeCastExpression[array.GetLength(0)]; 
     for (int j = 0; j < values.Length; j++) 
     { 
      values[j] = new CodeCastExpression(); 
      values[j].Expression = new CodePrimitiveExpression(array.GetValue(j)); 
      values[j].TargetType = new CodeTypeReference(array.GetType().GetElementType()); 
     } 

     arrayCreateExpression.Initializers.AddRange(values); 
    } 

    return arrayCreateExpression; 
    } 
+0

但我需要知道数组的第一个维度,对不对?我不能,看到我的编辑。无论如何,感谢一般情况下的实施。 –

0

您有以下的解决方法,以产生具有动态长度交错数组:

创建DOM等效的

ELEMENTTYPE[] array = (ELEMENTTYPE[])Array.CreateInstance(typeof(ELEMENTTYPE), length); 

ELEMENTTYPE可以是任何类型的,无论是一个数组或不。

0

这里是我的解决方案,使用CodeSnippetExpression

public static DOM.CodeExpression NewArray (this Type type, int dim, int size) { 
    string dims = String.Concat(Enumerable.Repeat("[]", dim - 1).ToArray()); 
    return new DOM.CodeSnippetExpression(string.Format("new {0}[{1}]{2}", type.FullName, size, dims)); 
}