Cơ chế liên kết hàm với đối tượng tại compile time gọi là early binding. Còn gọi là static binding. C# cung cấp 2 kỹ thuật đa hình tĩnh: Function overloading và Operator overloading.
Tìm hiểu Function Overloading với ví dụ:
Có thể có nhiều định nghĩa cho cùng tên hàm trong cùng scope. Định nghĩa phải khác nhau về kiểu và/hoặc số lượng tham số. Không thể overload chỉ khác kiểu trả về.
Ví dụ hoàn chỉnh:
Ví dụ
using System;
namespace PolymorphismApplication {
class Printdata {
void print(int i) {
Console.WriteLine("Printing int: {0}", i);
}
void print(double f) {
Console.WriteLine("Printing float: {0}", f);
}
void print(string s) {
Console.WriteLine("Printing string: {0}", s);
}
static void Main(string[] args) {
Printdata p = new Printdata();
// Call print to print integer
p.print(5);
// Call print to print float
p.print(500.263);
// Call print to print string
p.print("Hello C++");
Console.ReadKey();
}
}
}
Kết quả
Printing int: 5
Printing float: 500.263
Printing string: Hello C++