C# - Virtual modifier
FakeStandard
Posted on September 20, 2022
什麼是 virtual
?
它的定義很簡單,virtual
關鍵字可以使用於屬性、方法、索引子或事件定義,繼承內部具有 virtual
關鍵字成員的類別之子類別可以被覆寫,例如使用 virtual
關鍵字的方法,可以再子類別中使用 override
來覆寫此方法
class Shape
{
protected int size;
// 定義為虛擬方法
public virtual int GetArea()
{
return size * size;
}
}
class Rectangle : Shape
{
public Rectangle(int x, int y)
{
X = x;
Y = y;
}
public int X { get; }
public int Y { get; }
// 覆寫方法內容
public override int GetArea() => X * Y;
}
反之,如果覆寫的方法不是虛擬方法,編譯器會回報錯誤,例如下列 B 類別覆寫 Foo 方法會失敗
class F
{
public void Foo() { }
}
class B : F
{
public override void Foo() { }
}
編譯器回報被覆寫的方法至少必須是虛擬、抽象或覆寫的其中一種
virtual
修飾詞不可與 static
、abstract
、override
或 private
一起使用
嘗試將屬性定義為 virtual
,並在子類別覆寫該屬性
public class Person
{
// virtual property
public virtual string Name { get; set; }
}
public class Employee : Person
{
private string name;
// override property
public override string Name
{
get { return name; }
set
{
if (!string.IsNullOrEmpty(value))
name = value;
else
name = "Unknown";
}
}
}
練習使用 virtual
關鍵字
public class Shape
{
public const double PI = Math.PI;
protected double r, h;
public Shape() { }
public Shape(double r)
{
this.r = r;
}
public Shape(double r, double h)
{
this.r = r;
this.h = h;
}
// virtual method
public virtual double GetArea() => r;
}
public class Circle : Shape
{
public Circle(double r) : base(r) { }
// override method
public override double GetArea() => r * r * PI;
}
public class Cylinder : Shape
{
public Cylinder(double r, double h) : base(r, h) { }
public double GetVolume() => base.GetArea() * 2 * h;
}
Reference
Thanks for reading the article 🌷 🌻 🌼
If you like it, please don't hesitate to click heart button ❤️
or follow my GitHub ⭐ I'd appreciate it.
💖 💪 🙅 🚩
FakeStandard
Posted on September 20, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.