C#学习——继承、封装、多态
一、继承
1)什么是继承?
官方话:允许一个类继承另一个类的字段和方法
个人理解:子类可以使用父类已经授权的所有字段和方法,子承父业
2)使用方式
方式:子类:父类
class 父类
{
// 父类成员
}
class 子类 : 父类
{
// 子类成员
}
3)eg:
子类继承了父类,所以子类拥有父类的100块,同时子类还能学会了说英语
class Father
{public int moneny = 100;public void SayEnglish(){Console.WriteLine("说英语");}}class Son : Father
{}
static class Program
{static void Main(){Son son = new Son();son.SayEnglish(); //-->说英语Console.WriteLine("儿子有"+son.moneny+"元"); //-->儿子有100元}
}
二、封装:
1)控制权限
属性、方法、类等之前的访问修饰符,给予外部引用权限的
一个人A为父类,他的儿子B,妻子C,私生子D(注:D不在他家里)
public:所有对象都可以访问; 地球人都知道,全公开
private:对象本身在对象内部可以访问; 只有A知道(隐私?心事?)
protected:只有该类对象及其子类对象可以访问 A,B,D知道(A和他的所有儿子知道,妻子C不知道)
internal:同一个程序集的对象可以访问; A,B,C知道(A家里人都知道,私生子D不知道)
protected internal:访问限于当前程序集或派生自包含类的类型。 A,B,C,D都知道,其它人不知道
2)隐藏实现细节
// 构造函数:初始化账户余额public BankAccount(decimal initialBalance){_balance = initialBalance;}// 公共方法:存款(暴露给外部的接口)public void Deposit(decimal amount){if (amount <= 0)throw new ArgumentException("存款金额必须大于0");_balance += amount;}// 公共方法:取款(暴露给外部的接口)public void Withdraw(decimal amount){if (amount <= 0)throw new ArgumentException("取款金额必须大于0");if (amount > _balance)throw new InvalidOperationException("余额不足");_balance -= amount;}// 公共属性:只读访问余额(隐藏内部存储方式)public decimal Balance => _balance;
}class Program
{static void Main(){var account = new BankAccount(1000);account.Deposit(500); // 存款500account.Withdraw(200); // 取款200Console.WriteLine($"当前余额: {account.Balance}"); // 输出: 1300}
}
三、多态
1)什么是多态?
官方描述:相同的操作或方法可以作用于多种类型的对象上,产生不同的行为
个人理解:一个饼不同的吃法
2)编译时多态(方法重载):
方法名相同,但签名不同(参数列表不同)。
返回类型不影响重载。
public class Calculator
{// 方法重载:Add(int, int)public int Add(int a, int b){return a + b;}// 方法重载:Add(double, double)public double Add(double a, double b){return a + b;}// 方法重载:Add(int, int, int)public int Add(int a, int b, int c){return a + b + c;}
}// 使用
Calculator calc = new Calculator();
Console.WriteLine(calc.Add(1, 2)); // 输出:3
Console.WriteLine(calc.Add(1.5, 2.5)); // 输出:4
Console.WriteLine(calc.Add(1, 2, 3)); // 输出:6
3)运行时多态(方法重写)
继承和虚方法(virtual)或抽象方法(abstract)实现的
基类方法用virtual、派生类方法override
// 基类
public class Animal
{public virtual void MakeSound(){Console.WriteLine("Animal makes a sound.");}
}// 派生类
public class Dog : Animal
{public override void MakeSound(){Console.WriteLine("Dog barks.");}
}public class Cat : Animal
{public override void MakeSound(){Console.WriteLine("Cat meows.");}
}// 使用
Animal animal1 = new Animal();
Animal animal2 = new Dog();
Animal animal3 = new Cat();animal1.MakeSound(); // 输出:Animal makes a sound.
animal2.MakeSound(); // 输出:Dog barks.
animal3.MakeSound(); // 输出:Cat meows.