C# 中的多态性是什么?
csharpprogrammingserver side programming更新于 2025/10/15 4:52:17
多态性可以是静态的,也可以是动态的。静态多态性是指函数的响应在编译时确定。动态多态性是指函数的响应在运行时确定。
静态多态性是指函数的响应在编译时确定。动态多态性是指函数的响应在运行时确定。动态多态性就是我们所说的后期绑定。
编译时多态性或静态绑定
在编译时将函数链接到对象的机制称为早期绑定。它也被称为静态绑定。
运行时多态性或动态绑定
运行时多态性具有方法重写,也称为动态绑定或后期绑定。
让我们看一个实现方法重载的编译时多态性的示例 −
示例
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();
// 调用 print 打印整数
p.print(5);
// 调用 print 打印浮点数
p.print(500.263);
// 调用 print 打印字符串
p.print("Hello C++");
Console.ReadKey();
}
}
}
输出
Printing int: 5 Printing float: 500.263 Printing string: Hello C++

