C# 进阶 各种方法汇总(析构方法,虚方法,抽象方法,扩展方法)
各种方法汇总
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { /* * 静态方法:生命周期:一旦创建到应用结束才会结束;全局;效率高 * 用处:用户登录信息,系统配置信息,系统设置,SQLHelper * 注意:静态的东西创建多了占用内存会很大,不是必要情况不要创建静态对象 * 调用:静态方法调用非静态方法,不能直接调用,在类初始化后再调用 */ static void Main(string[] args) { } /* * 构造方法: * 用处:初始化对象,或者初始化一些数据 */ public Program() { } /* * 析构方法: * 作用:释放对象 * 谁在使用:GC垃圾回收器在调用 */ ~Program() { } /* * 虚方法: * 作用:允许子类/派生类 进行重写,也实现不一样的功能 * 特点:好维护 */ public virtual int Calculate(int a, int b) { return a + b; } } class Program1 : Program { //子类重写方法 //调用 new Program1().Calculate(); public override int Calculate(int a, int b) { return a + b + a + b; } } /// <summary> /// 抽象方法一定要写到抽象类中 /// </summary> public abstract class Program2 { /* * 抽象方法:规范好让子类实现 * 定义:一定要写道抽象类里面,而且不能new,不带方法体 * 使用场合:强制性一定要实现 * * 与接口的区别与使用场合: * 区别:1.抽象类--单继承,接口可以多继承 * 2.抽象类可以写普通方法,虚方法等,接口只能写规范,不能写实现 * * 使用场合:抽象类一般用于常用不会经常改动,然后抽象范围大一些的事件, * 接口适用于经常修改,只是一个规范的地方 */ public abstract int Calculate(int a, int b); //抽象类可以有虚方法 public virtual int Sub(int a,int b) { return a - b; } //抽象类可以有普通方法 public int Mul(int a,int b) { return a * b; } } public class Program3 : Program2 { //重写父类抽象方法 public override int Calculate(int a, int b) { throw new NotImplementedException(); } } /// <summary> /// 接口 /// </summary> public interface Program4_1 { int Add(int a, int b); } public interface Program4_2 { int Add(int a, int b); } public class Program5 : Program4_1,Program4_2 { public int Add(int a ,int b) { return a + b; } } /* * 扩展方法: * 定义:在非泛型静态类中,定义静态方法也就是扩展方法 * 扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。 扩展方法当然不能破坏面向对象封装的概念,所以只能是访问所扩展类的public成员。 扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。 * 使用场合:1. 调用密封类中的对象,属性或者方法(扩展密封类) * 2.扩展接口: */ /// <summary> /// 假如这个类是别人那里拿过来的,不是自己写的 /// 密封类,不能继承 /// </summary> public sealed class Program6 { public string Phone { get; set; } public string GetPhone() { return Phone; } } /// <summary> /// //定义一个静态类,再写一个静态方法 /// </summary> public static class Program7 { public static void ShowPhone(this Program6 program6) { Console.WriteLine(program6.GetPhone()); } } public class Program8 { /// <summary> /// 扩展方法 /// </summary> Program6 program6 = new Program6() { Phone = "123456789" }; void testc() { //调用扩展方法 program6.ShowPhone(); } } public interface ICalculate { int Add(int a, int b); } public static class InterfaceExtend { public static int Sub(this ICalculate calculate,int a,int b) { return a - b; } public static int Mul(this ICalculate calculate,int a, int b) { return a - b; } public static int Div(this ICalculate calculate,int a, int b) { return a - b; } } public class A : ICalculate { public int Add(int a, int b) { throw new NotImplementedException(); } } // 虽然A类只实现加法 ,但是现在可同过A类调用 减法 乘法 除法