如何用C#编写带有foreach的struct数组

时间:2017-02-14 02:16:28

标签: c# arrays struct foreach

在这里,我无法使用foreach

  

`错误CS0030无法将类型'ConsoleApplication5._3.Struct.Sach'转换为'int'

我该如何解决?

public struct Sach
{
    public string TenSach;
    public string TacGia;
    public string GioiThieu;
    public int ID;
    public void nhapdulieu(string q,string w, string e, int r)
    {
        TenSach = q;
        TacGia = w;
        GioiThieu = e;
        ID = r;
    }
    public void Insach()
    {
        Console.Write($"Ten sach: {TenSach}\n");
        Console.Write($"Tac gia: {TacGia}\n");
        Console.Write($"Gioi thieu: {GioiThieu}\n");
        Console.Write($"Ma sach: {ID}\n");
    }
};


public class QuanLySach
{
    public static void NhapSach()
    {

        Sach[] sach1 = new Sach[4];
        for(int i=0;i<4;i++)
        {
            Console.WriteLine("nhap ten sach, tac gia, gioi thieu, id:");
            sach1[i].TenSach = Console.ReadLine();
            sach1[i].TacGia = Console.ReadLine();
            sach1[i].GioiThieu = Console.ReadLine();
            var vv = Console.ReadLine();
            Int32.TryParse(vv, out sach1[i].ID);
        }

        foreach(int bb in sach1)
        {
         // in here i cant use foreach but i dont know why?
        }
        Console.ReadLine();
    }  
    }
}

1 个答案:

答案 0 :(得分:2)

您错误地使用了foreach。 Foreach循环将迭代槽序列,您的bb应该与该序列的基本类型相同。在你的情况下应该是:

foreach(Sach bb in sach1)
{
     // in here i cant use foreach but i dont know why?
}