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

后端 未结 10 1010
无人及你
无人及你 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:39

    The simple answer is variant is weakly typed while duck typing is strongly typed.

    Duck typing can be summed up nicely as "if it walks like a duck, looks like a duck, acts like a duck, then it's a duck." It computer science terms consider duck to be the following interface.

    interface IDuck {
      void Quack();
    }
    

    Now let's examine Daffy

    class Daffy {
      void Quack() {
        Console.WriteLine("Thatsssss dispicable!!!!");
      }
    }
    

    Daffy is not actually an IDuck in this case. Yet it acts just like a Duck. Why make Daffy implement IDuck when it's quite obvious that Daffy is in fact a duck.

    This is where Duck typing comes in. It allows a type safe conversion between any type that has all of the behaviors of a IDuck and an IDuck reference.

    IDuck d = new Daffy();
    d.Quack();
    

    The Quack method can now be called on "d" with complete type safety. There is no chance of a runtime type error in this assignment or method call.

提交回复
热议问题