2012-11-19 23 views
0

我与编码一个初学者,试图解决简单的问题:访问列表<T>值

我有三列清单,并试图存储在列表访问值。它给了我没有答案......任何想法?感谢

private void btnImage1Load_Click(object sender, EventArgs e) 
    { 
     openFileDialog1.ShowDialog(); 
     pictureBox1.ImageLocation = openFileDialog1.FileName;      
    } 

    public class ListThreeColumns 
    { 
     public int XCoord { get; set; } 
     public int YCoord { get; set; } 
     public Color Color { get; set; } 
    } 

    private List<ListThreeColumns> GetPixels() 
    { 
     Bitmap picture = new Bitmap(pictureBox1.Image); 

     List<ListThreeColumns> colorList = new List<ListThreeColumns> 
     { 

     }; 

     for (int y = 0; y < picture.Height; y++) 
     { 
      for (int x = 0; x < picture.Width; x++) 
      { 
       colorList.Add(new ListThreeColumns { XCoord = x, YCoord = y, Color = picture.GetPixel(x, y) }); 
      } 
     } 
     return colorList; 
    } 


    private void btnScanPixels_Click(object sender, EventArgs e) 
    { 
     List<ListThreeColumns> seznamBarev = GetPixels(); 
     MessageBox.Show(seznamBarev[6].ToString()); 


    } 
+1

[为什么集合初始值设定项表达式要求实现IEnumerable?](http://stackoverflow.com/q/3716626/299327) –

回答

4

在这一行:

MessageBox.Show(seznamBarev[6].ToString()); 

...你所访问列表的元件6,但后来只是打电话就可以了ToString。由于您尚未覆盖ListThreeElements(顺便提一下,它的名字可能更好,Pixel),这意味着结果不会特别有用。

你可以写:

ListThreeColumns pixel = seznamBarev[6]; 
MessageBox.Show(string.Format("{0}, {1} - {2}", pixel.X, pixel.Y, pixel.Color); 
0

那你想干什么? 如果你想在字符串中显示每个项目,你可以使用乔恩的方式。 但是最好将操作移动到您的班级。 如果您在ListThreeColumns类中重写'ToString()'方法,则代码将正常工作,且不会更改。

public class ListThreeColumns 
{ 
    public int XCoord { get; set; } 
    public int YCoord { get; set; } 
    public Color Color { get; set; } 

    public override ToString() 
    { 
     return string.Format("X={0}, Y={1}, Color=({2};{3};{4})", 
      this.XCoord , this.YCoord , Color.R,Color.G,Color.B); 
    } 
}