using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace 二維數組 { class Program { static void Main(string[] args) { int row = 0;//行 int col = 0;//lie FileStream fs; string path = @"C:\Documents and Settings\Administrator\桌面\1.txt"; fs = new FileStream(path, FileMode.Open, FileAccess.Read); StreamReader sr; sr = new StreamReader(fs); List<double[]> arrary = new List<double[]>(); while (!sr.EndOfStream) { string[] arr = sr.ReadLine().Split(' '); col = arr.Length; double[] temp=new double[col]; for (int x = 0; x < col; x++) { temp[x] = Convert.ToDouble(arr[x]); } arrary.Add(temp); for (int y = 0; y < col; y++) { Console.Write(arrary[row][y] + " "); } row++; Console.WriteLine("\n"); } sr.Close(); fs.Close(); Console.Read(); } } }
arrary定義的泛型 double數組類型。是二維數組的使用方法。能夠經過arrary[x][y],進行數據的讀取 .注意必須先add 每次add一次 ,x就加1.數組
若是arrary這樣定義 安全
List<double[,]> arrary = new List<double[,]>(); 那麼讀取數據應該這樣arrary[num][x,y] 每次add一次 num都會+1, add賦值時也必須是[,]的對象。
注意:.net中有一些非託管對象有close和dispose兩個方法,最安全的作法是先close 再 dispose。
後來啊 一看還有好多更簡單的作法了 你瞧:
public short[] readFile(string fileName) { string[] dt = File.ReadAllLines(fileName); short[] b = new short[dt.Length]; for (int i = 0; i < b.Length; i++) { b[i] = short.Parse(dt[i]); } return b; }
這就行了 ,簡單方便 多好spa