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