[英]How to use char array inside Struct in c#?
我正在嘗試在struct Books中實現char數組。 我已經在結構內部聲明了char數組public char [] b_id = new char [3]。 現在,我想訪問b_id並初始化一些值。 如何做呢。 有什么建議么? 這是我目前的代碼。
namespace @struct
{
struct Books
{
public string title;
public char[] b_id = new char[3];
};
class Program
{
static void Main(string[] args)
{
Books Book1; /* Declare Book1 of type Book */
/* book 1 specification */
Book1.title = "C Programming";
/* print Book1 info */
Console.WriteLine("Book 1 title : {0}", Book1.title);
Console.ReadKey();
}
}
}
您不能在結構中包含實例字段初始化程序(即,編譯器不允許您直接在Books結構中初始化b_id char數組)。 如果執行以下操作,則您的程序應該可以運行:
struct Books
{
public string title;
public char[] b_id;
};
void Main()
{
Books book1; /* Declare Book1 of type Book */
book1.b_id = new char[3] {'a', 'b', 'c'};
/* book 1 specification */
book1.title = "C Programming";
/* print Book1 info */
Console.WriteLine("Book 1 title : {0}", book1.title);
Console.WriteLine("Book att : {0}", book1.b_id[0]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.