What is the difference between static and dynamic binding?

前端 未结 6 799
予麋鹿
予麋鹿 2021-01-31 09:41

Binding times can be classified between two types: static and dynamic. What is the difference between static and dynamic binding?

Could you give a quick example of each

6条回答
  •  不要未来只要你来
    2021-01-31 10:35

    Static Binding: is the process of resolving types, members and operations at compile-time. For example:

    Car car = new Car();
    car.Drive();
    

    In this example compiler does the binding by looking for a parameterless Drive method on car object. If did not find that method! search for methods taking optional parameters, and if did not found that method again search base class of Car for that method, and if did not found that method again searches for extension methods for Car type. If no match found you'll get the compilation error!

    I this case the binding is done by the compiler, and the binding depends on statically knowing the type of object. This makes it static binding.

    Dynamic Binding: dynamic binding defers binding (The process of resolving types, members and operations) from compile-time to runtime. For example:

    dynamic d = new Car();
    d.Drive();
    

    A dynamic type tells the compiler we expect the runtime type of d to have Drive method, but we can't prove it statically. Since the d is dynamic, compiler defers binding Drive to d until runtime.

    Dynamic binding is useful for cases that at compile-time we know that a certain function, member of operation exists but the compiler didn't know! This commonly occurs when we are interoperating with dynamic programming languages, COM and reflection.

提交回复
热议问题