Is C# a single dispatch or multiple dispatch language?

后端 未结 8 1951
悲&欢浪女
悲&欢浪女 2020-12-02 20:25

I\'m trying to understand what single and multiple dispatch are, exactly.

I just read this:
http://en.wikipedia.org/wiki/Multiple_dispatch

And from that

相关标签:
8条回答
  • 2020-12-02 21:03

    For those that find this article using a search engine, C# 4.0 introduces the dynamic keyword. The code would look like the following.

    int CaptureSpaceShip(IRebelAllianceShip ship) {}
    int CaptureSpaceShip(XWing ship) {}
    
    void Main() {   
        IRebelAllianceShip theShip = new XWing();  
        CaptureSpaceShip((dynamic)theShip);
    }
    
    0 讨论(0)
  • 2020-12-02 21:15

    Maybe somebody will be interested in good C# example for multiple dispatch using dynamic keyword (MSDN blog)

    class Animal 
    { 
    }
    
    class Cat : Animal 
    { 
    }
    
    class Dog : Animal 
    { 
    }
    
    class Mouse : Animal 
    { 
    }
    

    We can create several overloads of the same method, specialized according to different combinations of their parameter types:

    void ReactSpecialization(Animal me, Animal other) 
    { 
        Console.WriteLine("{0} is not interested in {1}.", me, other); 
    }
    
    void ReactSpecialization(Cat me, Dog other) 
    { 
        Console.WriteLine("Cat runs away from dog."); 
    }
    
    void ReactSpecialization(Cat me, Mouse other) 
    { 
        Console.WriteLine("Cat chases mouse."); 
    }
    
    void ReactSpecialization(Dog me, Cat other) 
    { 
        Console.WriteLine("Dog chases cat."); 
    }
    

    And now the magic part:

    void React(Animal me, Animal other) 
    { 
        ReactSpecialization(me as dynamic, other as dynamic); 
    }
    

    This works because of the "as dynamic" cast, which tells the C# compiler, rather than just calling ReactSpecialization(Animal, Animal), to dynamically examine the type of each parameter and make a runtime choice about which method overload to invoke.

    To prove it really works:

    void Test() 
    { 
        Animal cat = new Cat(); 
        Animal dog = new Dog(); 
        Animal mouse = new Mouse();
    
        React(cat, dog); 
        React(cat, mouse); 
        React(dog, cat); 
        React(dog, mouse); 
    }
    

    Output:

    Cat runs away from dog.
    Cat chases mouse.
    Dog chases cat.
    Dog is not interested in Mouse.
    

    Wikipedia says that C# 4.0 (dynamic) is "multiple dispatch" language.
    I also think that languages such as Java, C# (prior to 4.0), C++ are single dispatch.

    0 讨论(0)
提交回复
热议问题