Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Overriding vs Shadowing trong C#

Overriding

Dưới overriding, định nghĩa hành vi đặc thù cho kiểu lớp con, triển khai phương thức cha theo yêu cầu.

Ví dụ abstract class triển khai Overriding:

Ví dụ

using System;

namespace PolymorphismApplication {
    abstract class Shape {
        public abstract int area();
    }
    class Rectangle : Shape {
        private int length, width;
        public Rectangle(int a = 0, int b = 0) {
            length = a;
            width = b;
        }
        public override int area() {
            Console.WriteLine("Rectangle 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();
        }
    }
}

Shadowing

Shadowing = method hiding. Phương thức cha có sẵn cho con không dùng override. Con có phiên bản riêng.

Dùng new để shadowing tạo phiên bản riêng của hàm cơ sở.

Ví dụ

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());
    }
}