0

我在下面概述的内容是否有正式名称。该示例在 c# 中,但前提将适用于其他语言。我几乎可以肯定我几年前在其他语言中做过类似的事情,但是是什么,或者这个概念的名称让我无法理解。动态调度(各种)??

我试图传达的关键点是,在运行时,要执行的方法被确定并被调用。这些方法将具有几乎相同的签名,只是参数的类型不同,并且参数也都在同一个继承树中。我知道我遗漏了一些细节,但我想让示例保持简单。

string result;
User u;
User user = new User();
Manager manager = new Manager();

u = user;
result = _Print(u);
Console.WriteLine(result); // user...

u = manager;
result = _Print(u);
Console.WriteLine(result); // manager...

// interested in part
private static string _Print(User u)
{
    return (u is Manager) ? Print((Manager)u) : Print(u);
}

// plumbing
private static string Print(User u)
{
    return "User...";
}
private static string Print(Manager m)
{
    return "Manager...";
}

class User { ... }
class Manager : User { ... }
4

1 回答 1

1

It is dynamic dispatch. I learn it as dynamic binding, because it is a function binding feature provided by many OO languages such as Java, that implements it by default, and C++, in which it requires in the explicit keyword "virtual" for it to work in a dynamic fashion - by default c++ is static binding. However, modern in OO the dynamic binding is easily achieved by Polimorphism and Overloading. So you can have something like this:

User u = new User(); 
Console.WriteLine(u.print()); // user...

u = new Manager();
Console.WriteLine(u.print()); // manager...


class User { ... 
    public string print(User u)
    {
        return "User...";
    }
... }
class Manager : User { ... 
    public string print(Manager m)
    {
        return "Manager...";
    }

... }

But you need to adapt to your language. I do not know much about C# and there are so many idiosyncrasies. I found this post with some examples for you - http://www.codeproject.com/KB/cs/dynamicbindingincsharp.aspx

于 2011-10-19T11:49:25.470 回答