Dynamic dispatch and binding

2020-02-25 08:02发布

问题:

Are dynamic dispatch and dynamic binding the same thing?

Thanks

Maciej

回答1:

No.

Dynamic Dispatch - The actual method group/signature/override chain is bound at compile time. The method called is dependent upon the actual runtime type of the object but no actual interpretation occurs. It will still be a version of the statically bound method.

Here is an example in C#.

class Foo { 
  public override string ToString() { return "foo's ToString"; }
}

void Example(object p1) { 
  p1.ToString();
}

The call to p1.ToString is an example of dynamic dispatch. The code statically binds to the method ToString. However it is a virtual method so the actual .ToString() called won't be known until runtime but it is guaranteed to call a .ToString() method. It will be the ToString of the actual type of p1. So if p1 is actually an instance of Foo, Foo::ToString will be called.

Dynamic Binding - The actual method is bound at runtime and is subject to interpretation based on the semantics of the language or reflection framework. This may fail due to an inability to bind.

Example:

void CallBar(object o) {
  var method = o.GetType().GetMethod("Bar");
  method.Invoke(new object[] {o});
}

In this case, we're attempting to invoke the method "Bar" on the object in question. The keyword is attempting. It's entirely possible that "Bar" will not exist on the object. But this is determined at runtime by dynamically binding to the method "Bar".

The thing they have the most in common, is both operations (likely) depend on the runtime type of the object.

EDIT

Added some more examples at the request of the OP



回答2:

Dynamic dispatch or dynamic binding means that when calling a method, choosing the actual method implementation to execute happens while the program is running, because statically there is not enough information available. It will based on the method name, the actual receiver type (subtype polymorphism), and/or the actual argument types (overloading), or even more fancy pattern matching.

Dynamic binding is, according to Wikipedia, a form of dynamic dispatch in OO languages where the actual method to invoke is based on the name of the operation and the actual receiver at runtime.

This article introduces statically-typed dynamic binding (dynamic binding aided by the static type system) and dynamic binding fully performed at runtime. It treats overloading as a form of dynamic binding as well.

I'm sure you can find many other articles that talk about dynamic dispatch or binding. As far as I can tell, the terminology is not fixed and 'overloaded'. It is best to describe what actually happens at runtime (the exact process of how a particular method is chosen) instead of trying to correctly define either of these two terms.



标签: c# java oop