Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c# - Dynamic dispatch and binding

Are dynamic dispatch and dynamic binding the same thing?

Thanks

Maciej

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...