|
dev
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
create the array using reflectionI have a type of System.Type. It indicates an primitive type such as Int32. I
try to use the following code to create an array Type arrayType = type.MakeArrayType(5); object objArray = Activator.CreateInstance(arrayType); but I got the following error: {"No parameterless constructor defined for this object."} Apparently, this is caused by the fact that the array type does not have a default constructor. How do I create the array using reflection? Roy wrote:
> I have a type of System.Type. It indicates an primitive type such as Int32. I I wrote the following app to examine the array's constructors:> try to use the following code to create an array > > Type arrayType = type.MakeArrayType(5); > object objArray = Activator.CreateInstance(arrayType); > > but I got the following error: > {"No parameterless constructor defined for this object."} > > Apparently, this is caused by the fact that the array type does not have a > default constructor. > How do I create the array using reflection? using System; using System.Reflection; namespace NewArray { class Program { static void Main(string[] args) { Type IntType = typeof(int); Type IntArrayType = IntType.MakeArrayType(5); ConstructorInfo[] Constructors = IntArrayType.GetConstructors(); foreach (ConstructorInfo Constructor in Constructors) { ParameterInfo[] Parameters = Constructor.GetParameters(); string[] Types = new string[Parameters.Length]; for (int Index = 0; Index < Parameters.Length; Index++) Types[Index] = Parameters[Index].ParameterType.Name; Console.WriteLine("({0})", String.Join(", ", Types)); } Console.ReadLine(); } } } // It gives the following output: (Int32, Int32, Int32, Int32, Int32) (Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32, Int32) // That is, you can pass either five lengths (one for each dimension) or five pairs of start/stop indices. Thus, int[, , , ,] A = (int[, , , ,]) Activator.CreateInstance(IntArrayType, 3, 3, 3, 3, 3); is exactly analagous to (but slower than) int[, , , ,] B = new int[3, 3, 3, 3, 3]; -- ..NET 2.0 for Delphi Programmers www.midnightbeach.com/.net Delphi skills make .NET easy to learn In print, in stores.
Other interesting topics
CultureInfo.NumericFormat and System.Convert
Unhandled Exception in Windows Service Where is the parameter argument collection? Using IPC question: one process as IPC client and server at same time problem. Preventing ThreadAbortException. .NET 2.0 Modifying Security.config file Books for building Frameworks css issue Sending chr(255) to serial port |
|||||||||||||||||||||||