在 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();
}
}
}方法隐藏(阴影)
阴影也称为方法隐藏。父类的在阴影中,无需使用 override 关键字即可为子类使用。子类有自己的相同函数版本。
使用 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());
}
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP