How is duck typing different from the old 'variant' type and/or interfaces?

后端 未结 10 998
无人及你
无人及你 2021-01-30 03:32

I keep seeing the phrase \"duck typing\" bandied about, and even ran across a code example or two. I am way too lazy busy to do my own research, can someone tel

10条回答
  •  鱼传尺愫
    2021-01-30 03:44

    @Kent Fredric

    Your example can most certainly be done without duck typing by using explicit interfaces...uglier yes, but it's not impossible.

    And personally, I find having well defined contracts in interfaces much better for enforcing quality code, than relying on duck typing...but that's just my opinion and take it with a grain of salt.

    public interface ICreature { }
    public interface IFly { fly();}
    public interface IWalk { walk(); }
    public interface IQuack { quack(); }
    // ETC
    
    // Animal Class
    public class Duck : ICreature, IWalk, IFly, IQuack
    {
        fly() {};
        walk() {};
        quack() {};
    }
    
    public class Rhino: ICreature, IWalk
    {
        walk();
    }
    
    // In the method
    List creatures = new List();
    creatures.Add(new Duck());
    creatures.Add(new Rhino());   
    
    foreach (ICreature creature in creatures)
    {
        if (creature is IFly)        
             (creature as IFly).fly();        
        if (creature is IWalk) 
             (creature as IWalk).walk();         
    }
    // Etc
    

提交回复
热议问题