......还是他们一样的东西?我注意到每个都有自己的维基百科条目:多态,多重调度,但我很难看到概念的不同之处.
编辑:重载如何适应这一切?
多态性是允许语言/程序在运行时根据发送到该方法的参数类型调用哪个方法来做出决策的工具.
语言/运行时使用的参数数量决定了语言支持的多态性的"类型".
单一调度是一种多态,其中只使用一个参数(消息的接收者 - this
或self
)来确定调用.
多分派是一种多态,其中多个参数用于确定调用哪个方法.在这种情况下,reciever以及类型方法的参数是用来告诉调用哪种方法.
因此,您可以说多态性是一般术语,多个和单个分派是特定类型的多态性.
附录:在编译期间发生重载.它使用编译期间可用的类型信息来确定要调用的方法类型.在运行时期间发生单个/多个调度.
示例代码:
using NUnit.Framework; namespace SanityCheck.UnitTests.StackOverflow { [TestFixture] public class DispatchTypes { [Test] public void Polymorphism() { Baz baz = new Baz(); Foo foo = new Foo(); // overloading - parameter type is known during compile time Assert.AreEqual("zap object", baz.Zap("hello")); Assert.AreEqual("zap foo", baz.Zap(foo)); // virtual call - single dispatch. Baz is used. Zapper zapper = baz; Assert.AreEqual("zap object", zapper.Zap("hello")); Assert.AreEqual("zap foo", zapper.Zap(foo)); // C# has doesn't support multiple dispatch so it doesn't // know that oFoo is actually of type Foo. // // In languages with multiple dispatch, the type of oFoo will // also be used in runtime so Baz.Zap(Foo) will be called // instead of Baz.Zap(object) object oFoo = foo; Assert.AreEqual("zap object", zapper.Zap(oFoo)); } public class Zapper { public virtual string Zap(object o) { return "generic zapper" ; } public virtual string Zap(Foo f) { return "generic zapper"; } } public class Baz : Zapper { public override string Zap(object o) { return "zap object"; } public override string Zap(Foo f) { return "zap foo"; } } public class Foo { } } }