简体   繁体   中英

How to write array of struct with foreach in C#

In here I can't use foreach :

`Error CS0030 Cannot convert type 'ConsoleApplication5._3.Struct.Sach' to 'int'

How can I fix it?

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();
    }  
    }
}

You are using foreach incorrectly. Foreach loop will iterate trough sequence and your bb should be same type as base type for that sequence. In your case it should be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM