ここで最良の定義が提供されているようですので、他のオブザーバーのために、私の2セントを追加させてください. それがもっと役立つことを願っています。
ポリモーフィズムには次の 2 種類があります。
1. Compile-time (static) polymorphism or (ad hoc) polymorphism.
それは単にメソッドのオーバーロードと演算子のオーバーロードです
2. Run time or (dynamic) polymorphism.
最初の用語は、Java および C++ の用語から継承されています。
しかし、.NETの用語では、2 番目の用語(ランタイム ポリモーフィズムを意味します) だけが実際にはポリモーフィズムと見なされ、単にポリモーフィズムと呼ばれます。
私が知る限り、(実行時)ポリモーフィズムを実装するには 3 つの方法があります。
1. Parametric polymorphism or simply the use of generics (templates in C++).
2. Inheritance-based polymorphism or subtyping.
3. Interface-based polymorphism.
インターフェイスベースのポリモーフィズムの簡単な例:
interface Imobile
{
void Move();
}
class Person :Imobile
{
public void Move() { Console.WriteLine("I am a person and am moving in my way."); }
}
class Bird :Imobile
{
public void Move() { Console.WriteLine("I am a bird and am moving in my way."); }
}
class Car :Imobile
{
public void Move() { Console.WriteLine("I am a car and am moving in my way."); }
}
class Program
{
static void Main(string[] args)
{
// Preparing a list of objects
List<Imobile> mobileList = new List<Imobile>();
mobileList.Add(new Person());
mobileList.Add(new Bird());
mobileList.Add(new Car());
foreach (Imobile mobile in mobileList)
{
mobile.Move();
}
// Keep the console open
Console.WriteLine("Press any key to exit the program:");
Console.ReadKey();
}
}
出力:
I am a person and am moving in my way.
I am a bird and am moving in my way.
I am a car and am moving in my way.
Press any key to exit the program: