Computer >> 컴퓨터 >  >> 프로그램 작성 >> C#

C#에서 함수 재정의와 메서드 숨기기의 차이점은 무엇입니까?

<시간/>

재정의

재정의에서 하위 클래스 유형에 고유한 동작을 정의할 수 있습니다. 이는 하위 클래스가 요구 사항에 따라 상위 클래스 메서드를 구현할 수 있음을 의미합니다.

Overriding을 구현하는 추상 클래스의 예를 살펴보겠습니다 −

예시

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 키워드를 사용하지 않고도 부모 클래스의 메서드를 자식 클래스에서 사용할 수 있습니다. 자식 클래스에는 동일한 기능의 자체 버전이 있습니다.

새 키워드를 사용하여 섀도잉을 수행합니다.

예를 들어 보겠습니다 -

예시

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