C#抽象类与重载重写实战

一,定义

1,抽象类:用于提供类的部分成员实现 , 包含抽象方法也可以是普通方法,如果抽象方法不用去实现,谁继承这个抽象谁去实现抽象方法 ,抽象类里面也可以定义抽象成员, 如果是抽象成员。 需要在派生类里面去实现成员。

需要重写抽象成员和抽象方法

2,重写: 使用override关键字进行重写

3,重载:函数重载 和 符号重载

【1】,符号重载:把常用算术符号,逻辑运算符号按照自己的定义方式进行运算 能够使对象进行运算

【2】,函数重载:在同一个作用域内定义多个同名函数,但这些函数的参数列表不同(参数类型、数量或顺序不同)。

二,相关习题

1,定义 Student 类,实现Study方法的重载。

相关代码:

namespace yw
{
internal class Program
{
static void Main(string\[\] args)
{
new Student();

new Student().Study();
new Student().Study("高数");
new Student().Study(150);
new Student().Study("语文", 150);
new Student().Study(120,"英语");

}
}
public class Student
{
public void Study()
{
Console.WriteLine("我在学习");
}
public void Study(string Progect)
{
Console.WriteLine("我在学习"+ Progect);
}
public void Study(int score)
{
Console.WriteLine("我在学习下次考{0}分",score);
}
public void Study(string projict, int score)
{
Console.WriteLine("我在学习{0} 下次考{1}分",projict,score);
}
public void Study(int score ,string project)
{
Console.WriteLine("我在学习{0} 下次考{1}分", project, score);

}
}
}

运行结果:

2,

定义一个抽象类 Animal 包含Name 名称 Color(颜色) Kind(种类) Favorite(喜好)四个属性 ,定义一个 带参数的构造函数,定义一个info的方法 打印以上四个信息,定义抽象的Have方法要求Dog和Cat俩个类继承Animal 实现Have这个抽象方法,狗类打印有骨头吃 猫类打印有鱼吃

相关代码:

namespace Zy
{
internal class Program
{
static void Main(string\[\] args)
{
Dog a1 = new Dog("小黄", "黄色", "金毛", "骨头");
a1.Info();
a1.Have(1);
Cat a2 = new Cat("小花", "黄色", "布偶", "鱼");
a2.Info();
a2.Have(1);

Console.ReadKey();

}
}
public abstract class Animal
{
public string Name { get; set; }
public string Color { get; set; }

public string Kind { get; set; }
public string Favorite { get; set; }
public Animal(string A, string C ,string K,string F)
{
Name = A;
Color = C;
Kind = K;
Favorite = F;

}

public void Info()
{
Console.WriteLine("姓名 "+Name +" 颜色 "+Color + " 种类 "+Kind +" 喜好 "+Favorite);

}
public abstract void Have(int a);

}
public class Dog : Animal
{
public Dog (string A, string C, string K, string F):base(A, C, K, F)
{

}

public override void Have(int a)
{
Console.WriteLine("有骨头吃");

}

}
public class Cat : Animal
{
public Cat(string A, string C, string K, string F) : base(A, C, K, F)
{

}

public override void Have(int a)
{
Console.WriteLine("有鱼吃");

}

}
}

运行结果:

相关推荐
雨落倾城夏未凉5 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫6 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫7 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6257 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902117 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠8 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫10 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech10 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf12 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m62512 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#