动态调度和绑定 [英] Dynamic dispatch and binding

查看:99
本文介绍了动态调度和绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

动态调度和动态绑定是否相同?

Are dynamic dispatch and dynamic binding the same thing?

谢谢

Maciej

推荐答案

不。

动态调度 - 实际的方法组/签名/覆盖链在编译时绑定。调用的方法取决于对象的实际运行时类型,但不会发生实际解释。它仍然是静态绑定方法的一个版本。

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.

这是C#中的一个例子。

Here is an example in C#.

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

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

对p1.ToString的调用是动态调度的一个例子。代码静态绑定到方法ToString。但是它是一个虚方法,因此调用的实际.ToString()在运行时才会知道,但保证调用.ToString()方法。它将是p1实际类型的ToString。因此,如果p1实际上是Foo的一个实例,则将调用Foo :: 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.

示例:

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

在这种情况下,我们试图调用方法Baron有问题的对象。关键字正在尝试。对象上完全不可能存在Bar。但这是在运行时通过动态绑定到方法Bar来确定的。

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.

编辑

根据OP的要求添加了更多示例

Added some more examples at the request of the OP

这篇关于动态调度和绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆