C#은 정적 다형성을 구현하는 두 가지 기술을 제공합니다. -
- 함수 오버로딩
- 연산자 과부하
함수 오버로딩
이름은 같지만 매개변수가 다른 두 개 이상의 메서드를 C#에서 함수 오버로딩이라고 합니다.
C#에서 함수 오버로딩은 인수의 수와 인수의 데이터 유형을 변경하여 수행할 수 있습니다.
숫자의 곱셈을 출력하는 함수가 있다고 가정해 보겠습니다. 그러면 오버로드된 메서드는 이름은 같지만 인수 수가 다릅니다. -
public static int mulDisplay(int one, int two) { }
public static int mulDisplay(int one, int two, int three) { }
public static int mulDisplay(int one, int two, int three, int four) { } 다음은 함수 오버로딩을 구현하는 방법을 보여주는 예입니다 -
예
using System;
public class Demo {
public static int mulDisplay(int one, int two) {
return one * two;
}
public static int mulDisplay(int one, int two, int three) {
return one * two * three;
}
public static int mulDisplay(int one, int two, int three, int four) {
return one * two * three * four;
}
}
public class Program {
public static void Main() {
Console.WriteLine("Multiplication of two numbers: "+Demo.mulDisplay(10, 15));
Console.WriteLine("Multiplication of three numbers: "+Demo.mulDisplay(8, 13, 20));
Console.WriteLine("Multiplication of four numbers: "+Demo.mulDisplay(3, 7, 10, 7));
}
} 출력
Multiplication of two numbers: 150 Multiplication of three numbers: 2080 Multiplication of four numbers: 1470
연산자 과부하
오버로드된 연산자는 키워드 operator 뒤에 정의되는 연산자에 대한 기호가 오는 특수 이름을 가진 함수입니다.
다음은 오버로드할 수 있는 연산자와 오버로드할 수 없는 연산자를 보여줍니다. -
| Sr.No | 연산자 및 설명 |
|---|---|
| 1 | +, -, !, ~, ++, -- 이러한 단항 연산자는 하나의 피연산자를 사용하며 오버로드될 수 있습니다. |
| 2 | +, -, *, /, % 이러한 이항 연산자는 하나의 피연산자를 사용하며 오버로드될 수 있습니다. |
| 3 | ==, !=, <,>, <=,>= 비교 연산자는 오버로드될 수 있습니다. |
| 4 | &&, || 조건부 논리 연산자는 직접 오버로드할 수 없습니다. |
| 5 | +=, -=, *=, /=, %= 할당 연산자는 오버로드할 수 없습니다. |
| 6 | =, ., ?:, -<, new, is, sizeof, typeof 이러한 연산자는 오버로드할 수 없습니다. |