在C#中覆盖vs阴影
覆写
在覆盖下,您可以定义特定于子类类型的行为,这意味着子类可以根据其要求实现父类方法。
让我们看一个实现Overriding的抽象类的示例-
示例
using System;
namespace PolymorphismApplication {
abstract class Shape {
public abstract int area();
}
class Rectangle: Shape {
private int length;
private int width;
public Rectangle( int a = 0, int b = 0) {
length = a;
width = b;
}
public override int area () {
Console.WriteLine("矩形类区域:");
return (width * length);
}
}
class RectangleTester {
static void Main(string[] args) {
Rectangle r = new Rectangle(10, 7);
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
}
}
}遮蔽
阴影也称为方法隐藏。父类的方法可用于子类,而无需在阴影中使用override关键字。子类具有相同功能的自己的版本。
使用new关键字执行阴影处理并创建自己的基类函数版本。
让我们看一个例子-
示例
using System;
using System.Collections.Generic;
class Demo {
public class Parent {
public string Display() {
return "家长班!";
}
}
public class Child : Parent {
public new string Display() {
return "儿童班!";
}
}
static void Main(String[] args) {
Child child = new Child();
Console.WriteLine(child.Display());
}
}热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便