要点:
1、结构概述
2、结构的使用
一 为什么需要结构
问题:
System.Drawing.Color有很多颜色值,它是一个枚举吗?

正常人眼可分辨的颜色种类可达几十万种以上
Color提供使用RGB值返回颜色的方法
FromArgb()
System.Drawing.Color是一个结构
1 结构定义
结构中有属性,也可以有方法。
结构是一种值的类型,通常用来封装一组相关的变量,结构中可以包括构造函数、常量、字段、方法、属性、运算符、事件和嵌套类型等,结构修饰符使用 struct。
public struct Rect //定义一个矩形结构
{
public double width; //矩形的宽
public double height; //矩形的高
public double Area() //矩形面积
{ return width * height;}
}
访问修饰符 struct 结构名
{
定义结构成员
}
public struct StructStudent
{
public string Name;
public int Age;
public string Hobby;
public int Popularity;
public void SayHi()
{
// ….
}
}

2 结构的使用1
结构实际是将多个相关的变量包装成为一个整体使用。在结构体中的变量,可以是相同、部分相同,或完全不同的数据类型,结构通常用于较小的数据类型,对于较大和复杂的数据类型建议使用类定义。
示例:
//…
StructStudent myStu;
myStu.Age = 20;
myStu.Gender = Genders.Female;
myStu.Hobby = "唱歌歌";
myStu.Name = "张靓靓";
myStu.Popularity = 100;
myStu.SayHi();
//…

3 结构使用2-2
示例:
struct StructStudent
{
//…
public StructStudent(string name, Genders gender, int age,
string hobby, int popularity)
{
this.Name = name;
this.Gender = gender;
//…
}
}
// …
StructStudent myStu =
new StructStudent("张靓靓", Genders.Female, 20, "唱歌歌", 100);
myStu.SayHi();
//…
4 类图
类图描述类的结构

5 通用的类图

6 理解结构与类的区别

7 值类型和引用类型
示例
static void Main(string[] args)
{
//使用值类型
StructStudent student1 = new StructStudent();
StructStudent student2 = new StructStudent();
student1.Age = 18;
student2 = student1;
student2.Age = 20;
Console.WriteLine("student1 = {0},student2 = {1}", student1.Age,
student2.Age);
}
static void Main(string[] args)
{
//使用引用类型
Student student1 = new Student();
Student student2 = new Student();
student1.Age = 18;
student2 = student1;
student2.Age = 20;
Console.WriteLine("student1 = {0},student2 = {1}", student1.Age,
student2.Age);
}

二 类和对象
问题:
举例说明什么是类,什么是对象?

类可以生成对象,类是对象的抽象。


操作Student类的字段和方法

三 对象
对象是人们要进行研究的任何事物

1 类和对象
类描述一组相似对象的共性。

2 类和对象的应用
类和对象的简单应用
示例:

3 类和类的成员

4 自定义一个类
回顾:使用过的自定义类DBHelper。

5 公有成员和私有成员

6 一种特别的方法

四 构造函数
是类中的一种特殊的方法
构造函数名与类名相同,不返回任何值
可初始化成员变量

1 使用构造函数
每次创建类的实例都会调用此方法

2 构造函数的重载

该文章在 2024/10/9 12:30:18 编辑过