我正在尝试在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();
}
}
}
答案 0 :(得分:0)
您不能在结构中使用实例字段初始值设定项(即编译器不允许您直接在Books结构中初始化b_id字符数组)。 如果您执行以下操作,您的程序应该可以运行:
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]);
}