Các từ khóa virtual được sử dụng để sửa đổi một method or property được khai báo, trong trường hợp này, method or property được gọi là virtual member. Cách thực thi của virutal member có thể bị thay đổi bằng cách override tại lớp kế thừa
Khi một virtual method được gọi, hệ thống sẽ kiểm tra xem nó có được override hay không. Nếu có thì nó sẽ thực thi override tại lớp chứa override, nếu không thì nó sẽ thực thi virtual member đã được định nghĩa ngay tại lớp đó.
Mặc định, các method không được khai báo virtual thì không thể override
Không thể sử dụng virtual với các từ khóa sau trong quá trình khai báo: static, abstract, override
Virtual property chạy giống abstract method, ngoại trừ sự khác biệt trong cách khai báo
Code:
// cs_virtual_keyword.cs
// Virtual and override
using System;
class TestClass
{
public class Dimensions
{
public const double pi = Math.PI;
protected double x, y;
public Dimensions()
{
}
public Dimensions (double x, double y)
{
this.x = x;
this.y = y;
}
public virtual double Area()
{
return x*y;
}
}
public class Circle: Dimensions
{
public Circle(double r): base(r, 0)
{
}
public override double Area()
{
return pi * x * x;
}
}
class Sphere: Dimensions
{
public Sphere(double r): base(r, 0)
{
}
public override double Area()
{
return 4 * pi * x * x;
}
}
class Cylinder: Dimensions
{
public Cylinder(double r, double h): base(r, h)
{
}
public override double Area()
{
return 2*pi*x*x + 2*pi*x*y;
}
}
public static void Main()
{
double r = 3.0, h = 5.0;
Dimensions c = new Circle(r);
Dimensions s = new Sphere(r);
Dimensions l = new Cylinder(r, h);
// Display results:
Console.WriteLine("Area of Circle = {0:F2}", c.Area());
Console.WriteLine("Area of Sphere = {0:F2}", s.Area());
Console.WriteLine("Area of Cylinder = {0:F2}", l.Area());
}
}
kết quả:
Area of Circle = 28.27
Area of Sphere = 113.10
Area of Cylinder = 150.80
trong code của bạn
ở đoạn 1 là cách override áp dụng cho những method không có từ khóa virtual
đoạn 2: sử dụng virtual
đoạn 3: override ở lớp cha và cho phép lớp kế thừa nó override
cách viết
Button button = new Button();
Window wbutton = new Button();
button.DrawWindow();
wbutton.DrawWindow();
đều gọi method DrawWindow() đã được implement ở class Button
Bookmarks