1.实例演示:
2.结构体(Struct)定义说明:
在 C# 中,结构体(struct)是一种值类型(value type),用于组织和存储相关数据。结构体是值类型的数据结构,这样使得一个单一变量可以存储各种数据类型的相关数据,这个在需要很多初始化变量的时候很有用。struct 是关键字。
3.示例Books的结构体定义===>先定义
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
4.示例Books的结构体声明===>后使用
Books Book1= new Books(); /* 声明 Book1,类型为 Books */
Books Book2= new Books(); /* 声明 Book1,类型为 Books */
注意:一定是定义==>然后声明==>最后应用;
5.完整代码:
cs
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
Books Book1= new Books(); /* 声明 Book1,类型为 Books */
Books Book2= new Books(); /* 声明 Book1,类型为 Books */
private void button9_Click(object sender, EventArgs e)
{
/* book 1 详述 */
Book1.title = "C#";
Book1.author = "张三";
Book1.subject = "C#编程基础";
Book1.book_id = 123456;
/* book 2 详述 */
Book2.title = "C#";
Book2.author = "李四";
Book2.subject = "C#编程高级";
Book2.book_id = 456789;
comboBox1.SelectedIndex = 0;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.Items.Clear();
switch (comboBox1.SelectedIndex)
{
case 0:
listBox1.Items.Add(Book1.title);
listBox1.Items.Add(Book1.author);
listBox1.Items.Add(Book1.subject);
listBox1.Items.Add(Book1.book_id);
break;
case 1:
listBox1.Items.Add(Book2.title);
listBox1.Items.Add(Book2.author);
listBox1.Items.Add(Book2.subject);
listBox1.Items.Add(Book2.book_id);
break;
default:
break;
}
}