Multiple dispatch çoğu programla dilinde yoktur. Açıklaması şöyle
C#This is a form of polymorphism. You can compare it to subtype polymorphism of the kind offered by OOP languages that support class inheritance. Those languages usually resorts to single dispatch, at runtime, to choose an implementation to satisfy a virtual call. Single dispatch in this case is based on the type of the object at runtime (a single value). Multiple dispatch can choose which way to go based on multiple values. You have a function type, multiple implementations and we polymorphically choose one at runtime based on one of multiple acceptable values, hence multiple dispatch.In languages that support multi-methods (e.g. Clojure), this is not a problem at all because the language itself can express this relationship between a specific value and a function that needs to be called for it.
C#'ta dynamic kelimesi ile nesnenin gerçek tipi kullanılabilir.
Örnek
Elimizde şöyle bir hiyerarşi olsun
abstract class SpaceObject{public SpaceObject(int size) => Size = size;public int Size { get; }}class Asteroid : SpaceObject{public Asteroid(int size) : base(size) { }}class Spaceship : SpaceObject{public Spaceship(int size) : base(size) { }}
Bu hiyerarşiyi kullanan şöyle bir kod olsun. Burada "as dynamic" ile nesne gerçek tipine döndürülüyor. Eğer iki nesne de büyükse "Big boom!" yazar, eğer iki nesne de küçükse parametre tipleriner göre doğru metod çağrılır.
static class Collider { public static string Collide(SpaceObject x, SpaceObject y) => ((x.Size > 100) && (y.Size > 100)) ? "Big boom!" : CollideWith(x as dynamic, y as dynamic); private static string CollideWith(Asteroid x, Asteroid y) => "a/a"; private static string CollideWith(Asteroid x, Spaceship y) => "a/s"; private static string CollideWith(Spaceship x, Asteroid y) => "s/a"; private static string CollideWith(Spaceship x, Spaceship y) => "s/s"; }
Bu hiyerarşiyi kullanan şöyle bir kod olsun
Collider.Collide(new Asteroid(101), new Spaceship(300))); Collider.Collide(new Asteroid(10), new Spaceship(10))); Collider.Collide(new Spaceship(101), new Spaceship(10)));
Hiç yorum yok:
Yorum Gönder