简体   繁体   中英

How to use CodeVariableDeclaraionStament to declare Arrays

CodeVariableDeclarationStatement cvds = new CodeVariableDeclarationStatement(p.ParameterType, p.Name,
                       new CodePrimitiveExpression(INTARR()));

Consider the above code. and when i run my project in debug mode,these are the values that get stored in p.ParameterType and p.Name.

p.ParameterType = {Name = "Int32[]" FullName = "System.Int32[]"}
p.Name = "x"

and INTARR() is a method that returns an Array of Integers.

but i get the error, "Invalid Primitive Type: System.Int32[]. Consider using CodeObjectCreateExpression."

How can i use CodeObjectCreateExpression for the above code,ie I want to pass an Array of integers in CodeVariableDeclarationStatement.?

Arrays are not primitive. You need to use CodeArrayCreateExpression:

Int32[] ints = INTARR();
CodeExpression[] intExps = new CodePrimitiveExpression[ints.Length];
for (int i = 0; i < ints.Length; i++)
   intExps[i] = new CodePrimitiveExpression(ints[i]);
CodeVariableDeclarationStatement cvds = new CodeVariableDeclarationStatement(
   "Int32[]", "x", new CodeArrayCreateExpression("Int32", intExps));

based on this link I think it should be like this

CodeVariableDeclarationStatement cvds = new CodeVariableDeclarationStatement(typeof(Int32[]), "x",
                       new CodePrimitiveExpression(INTARR()));

So maybe this?:

CodeVariableDeclarationStatement cvds = new CodeVariableDeclarationStatement(typeof(Int32[], "x",
                       new CodePrimitiveExpression(INTARR()));                     

p.ParameterType = typeof(Int32);
p.Name = "x";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM