Csharp/CSharp Tutorial/Data Structure/Array CreateInstance

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Create Array With Bounds

using System;
    public  class MainClass 
    {
        static void Main()
        {
            int[] lengthsArray = new int[2] { 3, 5 };
            int[] boundsArray = new int[2] { 2, 3 };
            Array multiDimensionalArray = Array.CreateInstance(typeof(String), lengthsArray, boundsArray);
            for  (int i = 0; i < multiDimensionalArray.Rank; i++)
                Console.WriteLine("{0}:\t{1}\t{2}", i,multiDimensionalArray.GetLowerBound(i),multiDimensionalArray.GetUpperBound(i));
        }
    }

Dynamic array creation

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

public class MainClass
{
    public static void Main()
    {
        string[] myArray = (string[])Array.CreateInstance(typeof(string), 15);
        Console.WriteLine(myArray.GetType());
        Console.WriteLine(myArray.GetLength(0));
        Console.WriteLine(myArray.GetLowerBound(0));
        myArray.SetValue("Hello, array", 5);
        Console.WriteLine(myArray.GetValue(5));
    }
}
System.String[]
15
0
Hello, array

Use Array.CreateInstance to create array instance

using System;
public class MainClass
{
  public static void Main() {
    // Create and initialize a new Array instance.
    Array strArr = Array.CreateInstance( typeof(String), 3 );
    strArr.SetValue( "M", 0 );
    strArr.SetValue( "C", 1 );
    strArr.SetValue( "T", 2 );
        
    // Display the values of the Array.
    Console.WriteLine( "Initial Array values:" );
    for ( int i = strArr.GetLowerBound(0); i <= strArr.GetUpperBound(0); i++ )
      Console.WriteLine( strArr.GetValue( i ) );
  }
}
Initial Array values:
M
C
T