2010-10-22 10 views
8

Hey ragazzi, sono un po 'perso su come farlo. So come inizializzare un array con i valori al momento della dichiarazione, ma come lo farei con un array di tipo DateTime poiché richiede più argomenti per creare una data ??C#: inizializza un array DateTime

risposta

32

Intendi questo?

DateTime[] dateTimes = new DateTime[] 
{ 
    new DateTime(2010, 10, 1), 
    new DateTime(2010, 10, 2), 
    // etc 
}; 
+0

Sembra abbastanza semplice. L'uso della nuova parola chiave non causerà problemi? – Sinaesthetic

+0

Nessuna memoria data. È una matrice di oggetti DateTime, quindi al suo interno deve essere un'istanza della classe DateTime. – Necronet

+0

ok, l'ho provato senza la nuova parola chiave. Sembra funzionare bene solo con {DateTime (x, x, x)} ecc. Ero solo preoccupato che la nuova parola chiave avrebbe creato nuovi oggetti per ogni valore, cosa di cui non avevo bisogno. Grazie! – Sinaesthetic

5
DateTime [] startDate = new DateTime[5]; 
     startDate[0] = new DateTime(11, 11, 10); 
     startDate[1] = new DateTime(11, 11, 10); 
     startDate[2] = new DateTime(11, 11, 10); 
     startDate[3] = new DateTime(11, 11, 10); 
     startDate[4] = new DateTime(11, 11, 10); 
+2

L'ultima riga causerà un errore, in quanto ci sono solo 5 elementi nella matrice. – Matt

0
DateTime [] "name_of_array"=new Date[int lenght_of_the_array]; //this is the array DateTime 

E poi, quando si assegna il valore in ogni posizione dell'array:

DateTime "name_of_each_element_of_the_array"= new DateTime(int value_of_year,int value_of_month, int value_of_day);//this is each element that is added in each position of the array 
0
For example, i want to add a DateTime array of 4 elements:      DateTime[] myarray=new DateTime [4]; //the array is created 
int year, month, day;    //variables of date are created    
for(int i=0; i<myarray.length;i++) 
{ 
    Console.WriteLine("Day"); 
    day=Convert.ToInt32(Console.ReadLine()); 
    Console.WriteLine("Month"); 
    month=Convert.ToInt32(Console.ReadLine()); 
    Console.WriteLine("Year"); 
    year=Convert.ToInt32(Console.ReadLine()); 

    DateTime date =new DateTime(year,month,day); //here is created the object DateTime, that contains day, month and year of a date 

myarray[i]=date; //and then we set each date in each position of the array 
} 
+0

Questo non viene inizializzato in _time of declaration_. – namezero

1

Se si vuole costruire una matrice per intervallo di tempo tra due date potresti fare qualcosa del genere:

 timeEndDate = timeStartDate.AddYears(1); // or .AddMonts etc.. 
     rangeTimeSpan = timeEndDate.Subtract(timeStartDate); //declared prior as TimeSpan object 
     rangeTimeArray = new DateTime[rangeTimeSpan.Days]; //declared prior as DateTime[] 

     for (int i = 0; i < rangeTimeSpan.Days; i++) 
     { 
      timeStartDate = timeStartDate.AddDays(1); 
      rangeTimeArray[i] = timeStartDate; 
     }