av28779788?p=92视频学习笔记
- 当前为-->第二部分:C#基础
类和对象
什么是类什么是对象
以下是老婆类对象的内存存放示意图:
访问修饰符
属性
构造方法
this关键字
如下,演示构造方法即构造方法的重载:
类结构
学写集合类
下面学着写1个集合类,共3个文件:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _03类和对象_02学写集合类 {
class User {
//字段都是私有的,仅供类内部交流使用
private string _name;
private string _password;
//属性都是公开的,开放给类外部供使用.
public string Name { get => _name; set => _name = value; }
public string Password { get => _password; set => _password = value; }
//以下三个构造方法重载
public User() { }
public User(string name) {
this.Name = name;
}
public User(string name,string password):this(name) {
this.Password = password;
}
public void ShowUserInfo() {
Console.WriteLine("用户名称:{0}",Name);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _03类和对象_02学写集合类 {
class UserList {
//********私有字段************
private User[] data;
private int currentIndex;
//********公开属性************
public int Count { get => currentIndex; }
//********构造方法************
public UserList():this(8) {
//data = new User[8];
}
public UserList(int capacity) {
data = new User[capacity];
}
//********方***法************
public void Add(User value) {
CheckCapacity();
data[currentIndex++] = value;
}
public User GetElement(int index) {
return data[index];
}
private void CheckCapacity() {
//如果data数组容量不够?
//那就①开辟更大的数组;②拷贝原始数据;③替换引用
if (currentIndex>=data.Length) {//如果当前索引大于等于data数组长度
User[] newdData = new User[data.Length * 2];//new1个数组,容量翻倍
data.CopyTo(newdData, 0);//将原数组data从0号元素开始复制到新数组newData
data = newdData;//现在更新:将data引用指向newdata
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _03类和对象_02学写集合类 {
class Program {
static void Main(string[] args) {
UserList list = new UserList(3);
list.Add(new User("张三疯"));
list.Add(new User("王二麻子"));
list.Add(new User("赵四"));
list.Add(new User("孙悟空"));
for (int i=0;i<list.Count;i++) {
User user = list.GetElement(i);
user.ShowUserInfo();
}
}
}
}
List<>泛型集合
上面自写的集合类,现在我们换用C#的List<>泛型集合类:
字典集合
static
继承
static
以下演示了静态成员,静态类:
注意:非静态类可以有非静态成员,也可以有静态成员;
静态类只能有静态成员!
jiegou
以下为自开发的二维数组助手类(暂时略)
av28779788?p=106(暂时略,回头补上)
结构
如果结构体中有自动属性,例如:
在构造函数中必须先调用默认的无参构造函数(系统强制提供,看不见,且自己不能手动写无参构造函数)
或者,也可以不使用自动属性。