C#面向对象基础介绍
1、属性和字段
----------------------------------------------------------------------
// 属性首字母大写,字段首字母小写以下划线开头,如:_username
// 不建议使用字段,直接使用属性
public string Username { set; get; }
public int Age {
set {
if (value < 0 || value > 200) {
Age = 0;
} else {
Age = value;
}
}
get { return Age; }
}
public char Sex {
set {
if (value == '男' || value == '女') {
Sex = value;
} else {
Sex = '男';
}
}
get { return Sex; }
}
2、构造方法
public Person() {}
public Person(string username)
{
Username = username;
}
public Person(string username, int age) : this(username)
{
Age = age;
}
public Person(string username, int age, char sex) : this(username, age)
{
Sex = sex;
}
3、new
1.创建对象
2.隐藏父类的成员
4、this
1.代表当前类的对象
2.显示的调用自己的构造函数
5、base
1.显示调用父类的构造函数
2.调用父类的成员
6、is/as
----------------------------------------------------
// is 判断对象是否属于某个类
// as 将对象转换为某个类对象,转换失败返回null
Person obj = new Student();
if (obj is Student) {
Student student = obj as Student;
}
7、封装
public
private
私有,仅当前类可访问
protected
当前类及子类
internal
当前程序集
protected internal
当前程序集中的子类
8、继承
A:B,C,D
9、多态
多态的目的:使用同一个接口实现不同的功能
-----------------------------------------------------------
virtual
虚方法
-----------------------------------------------------------
override
重写父类方法
------------------------------------------------------------
abstract
修饰抽象类或抽象方法
10、接口
接口:接口表示一种能力,表示一种规范,统一使用方法
interface 声明一个接口
接口继承:
A:B,C,D
其中继承的类必须放在最前面
11、索引器,语法类似于属性
public string this[int index] {
set { Names[index] = value; }
get { return Names[index]; }
}