【C#】课堂知识点#4

 

1、回顾类中基本结构。

 

成员分为: 

a、(数据成员) , b、(方法成员)

数据成员: 字段

方法成员:方法,构造函数,属性,索引器,运算符。

 

属性的作用:

对字段进行访问提供get,set方法。

 

类中的字段通常用private修饰,通常用方法间接访问。

 

2、学会了派生,继承

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace MyProject
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             Shape s1 = new Shape(1, 2);
13             Console.WriteLine(s1);
14 
15             Box b1 = new Box(3, 4, 5);
16             Console.WriteLine(b1);
17 
18 
19             /*
20              * 父类指针可以 实例化子类对象,实现多态
21              */
22             Shape b2 = new Box(5, 6, 7);
23             Console.WriteLine(b2);
24         }
25     }
26     
27     public class Shape
28     {
29         private int length;
30         private int width;
31 
32         public int Length { get => length; set => length = value; }
33         public int Width { get => width; set => width = value; }
34 
35         public Shape ( int length , int width)
36         {
37             this.Length = length;
38             this.Width = width; 
39         }
40         public Shape():this(0, 0) { }
41         public override string ToString()
42         {
43             return string.Format("Shape -> length:{0}\t width:{1}", length, width);
44         }
45         #region 主要注释
46         /*
47          * 类中的字段属性封装
48          * 构造函数 : 两参数,零参数
49          * 重载ToString类
50          */
51         #endregion
52     }
53 
54     public class Box : Shape
55     {
56         private int height;
57         public int Height { get => height; set => height = value; }
58         public Box(int length, int width, int height):base(length, width){
59             this.height = height;
60         }
61         public Box() : this(0, 0, 0) { }
62         public override string ToString()
63         {
64             return string.Format("Box -> length:{0}\t width:{1}\t height:{2}", Length, Width, height);
65         }
66         #region Box类
67 
68         /*
69          *  Box继承了Shape的所有结构
70          *
71          *  1、无法直接访问父类的字段,但可通过"属性"间接访问
72          *  2、在重载 构造函数时,可以直接调用父类的构造函数实现部分字段的赋值
73          *  
74          */
75         #endregion
76     }
77 }
上课代码

 

posted @ 2019-09-29 20:24  Osea  阅读(236)  评论(0编辑  收藏  举报