2012-07-24 1 views
1

Voici un code C#.La méthode GetLength() ne fonctionne pas comme prévu sur un tableau

Il fournit le texte suivant:

tab.Length = 6 
tab.Rank = 2 
Length of dim 0 of tab : 0 
Length of dim 1 of tab : 1 

J'attend le texte suivant:

tab.Length = 6 
tab.Rank = 2 
Length of dim 0 of tab : 2 
Length of dim 1 of tab : 3 

Pourquoi pas? Merci.

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace TableTest 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      int[,] tab = new int[2, 3]; 

      for (int i = 0; i < 2; i++) 
      { 
       for (int j = 0; j < 3; j++) 
       { 
        tab[i, j] = 2 * i + j; 
       } 
      } 
      Console.WriteLine("tab.Length = {0}", tab.Length); 
      Console.WriteLine("tab.Rank = {0}", tab.Rank); 
      for (int i = 0; i < tab.Rank; i++) 
      { 
       Console.WriteLine("Length of dim {0} of tab : {0} ", i, tab.GetLength(i)); 
      } 

     } 
    } 
} 

Répondre

11

conjecture sauvage: votre dernière chaîne de format est erroné:

Console.WriteLine("Length of dim {0} of tab: {0} ", i, tab.GetLength(i)); 

Vous utilisez deux fois {0}, de sorte que vous êtes sortie la valeur de i dans les deux espaces réservés.

Utilisez ce lieu:

Console.WriteLine("Length of dim {0} of tab: {1} ", i, tab.GetLength(i)); 
+1

@EdS. Eh bien, ça aurait pu être une faute de frappe dans l'exemple de code, et je n'ai pas vraiment testé ça. Donc, "Estimated edumacated" alors. – millimoose

1

Votre chaîne de format est erroné. Remplacer "Length of dim {0} of tab : {0} " par "Length of dim {0} of tab : {1} ".

lui a en fait Votre code i, et non tab.GetLenght (i)

1

Avez-vous besoin simplement d'accéder au second paramètre passé à la Console.WriteLine? Essayez ceci:

Console.WriteLine("Length of dim {0} of tab : {1} ", i, tab.GetLength(i)); 
+0

Merci! Ça marche. – mistergreen

Questions connexes