我試圖做的是閱讀的三角形從文本文件中的座標命名爲「p102_triangles」,其數據是這樣的:讀三角從文本文件中的座標,並把它們放在三角形類C#
- 340495,-153,-910,835,-947
-175,41,-421,-714,574,-645
-547,712,-352,579,951,-786
419,-864,-83,650,-399,171
- 429,-89,-357,-930,296,-29
-734,-702,823,-745,-684,-62
...
到目前爲止,我做了一個三角形類,接受所有頂點的三個點類型值。每個點都有自己的(x,y)座標。然後我逐行讀取文件。在每一行中,我分隔逗號分隔值,將它們轉換爲整數並將它們存儲在大小爲6的數組中(每個三角形對於3個頂點有6個座標)。我創建類三角形的對象並將這個值分配給每個對象。所以基本上在每行之後創建一個三角形的對象。這是我的代碼,它以我想要的方式工作。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace triangleContainment
{
//Triangle class
public class triangle
{
public Point point1;
public Point point2;
public Point point3;
public triangle(Point point1, Point point2, Point point3)
{
this.point1 = point1;
this.point2 = point2;
this.point3 = point3;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//Global variables
List<int> pos = new List<int>(new int[6]);
List<triangle> triangle = new List<triangle>(new triangle[10000]);
private void readValues() //start of reading file function
{
char[] delimiterChars = { ',' };
System.IO.StreamReader file = new System.IO.StreamReader(@"C:\Users\DaVinci\Google Drive\C# Cloud\triangleContainment\triangleContainment\p102_triangles.txt");
string line;
int index = 0;
while ((line = file.ReadLine()) != null)
{
string[] values = line.Split(delimiterChars);
int i = 0;
foreach (string v in values)
{
pos[i] = Int32.Parse(v);
i++;
}
triangle[index] = new triangle(new Point(pos[0], pos[1]), new Point(pos[2], pos[3]), new Point(pos[4], pos[5]));
index++;
}
}//end of reading file function
private void Form1_Load(object sender, EventArgs e)
{
readValues();
}
}
}
因爲我是C#的新手,我只是從頭開始做的。我怎樣才能讓它更好或更短?我怎樣才能更有效地定義我的三角形類?我可以使用收藏以外的任何東西嗎?
當你使用一個基於流的類(如StreamReader的),你應該換了它的用法在[使用](https://開頭MSDN。 microsoft.com/en-us/library/yh598w02.aspx)塊,以確保它得到清理。在你的情況下,該文件永遠不會被關閉,直到你的應用程序終止並且操作系統清理完畢。 – Xavier