C# 中函数覆盖和方法隐藏的区别是什么?
覆盖
在覆盖项下,可以定义特定于子类类型的一种行为,这意味着子类可以基于自己的要求实现父类方法。
我们来看一个实现覆盖的抽象类示例 −
示例
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("Rectangle class area :");
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();
}
}
}方法隐藏(阴影)
阴影也称为方法隐藏。在阴影化中,父类的方法对子类可用,而无需使用覆盖关键字。子类有它自己版本的同名函数。
使用 new 关键字执行阴影。
我们来看一个示例 −
示例
using System;
using System.Collections.Generic;
class Demo {
public class Parent {
public string Display() {
return "Parent Class!";
}
}
public class Child : Parent {
public new string Display() {
return "Child Class!";
}
}
static void Main(String[] args) {
Child child = new Child();
Console.WriteLine(child.Display());
}
}
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP