一个物体拥有的属性的集合是一个结构体,比如一本书

书拥有的属性有标题、价格、作者、编码等这些属性,这些属性集合起来就是一本书的结构

下面是代码中的样子

struct Books{
	private string title;
  private double price;
  private string author;
  private string code;
}; // 以分号结尾

把结构体当作类使用就行,但是区别在于结构体 不能继承不能声明默认构造函数、是值类型(类是引用类型)

// 偷个懒,main()这样写是不规范的
main()
{
	Books b = new Books();
  b.title = "C#自学";
  b.price = 5.2;
  b.author = "打字机";
  b.code = "X5647395638";
  
  Console.WriteLine(b.title);
  Console.WriteLine(b.price);
  Console.WriteLine(b.author);
  Console.WriteLIne(b.code);
}

输出:

C#自学

5.2

打字机

X5647395638

给结构体写上自定义方法

struct Books{
	private string title;
  private double price;
  private string author;
  private string code;
  
  public void setValues(string t, double p, string a, string c)
  {
  	title = t;
    price = p;
    author = a;
    code = c;
  }
  
  public void WriteAll()
  {
  	Console.WriteLine(title);
    Console.WriteLine(price);
    Console.WriteLine(author);
    Console.WriteLIne(code);
  }
};

class study{
  
	main()
  {
  	Books b = new Books();
    b.setValue("C#自学" ,5.2 ,"打字机" ,"X5647395638");
    b.WriteAll();
  }
  
}

输出:

C#自学

5.2

打字机

X5647395638

加客服微信:qsiq17,开通VIP下载权限!VIP全站资源免费下载!!!