簡體   English   中英

如何在 C# 中使用 foreach 編寫結構數組

[英]How to write array of struct with foreach in C#

在這里我不能使用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();
    }  
    }
}

您錯誤地使用了foreach Foreach 循環將迭代槽序列,您的bb應該與該序列的基本類型相同。 在你的情況下,它應該是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM