我是一名学习 Objective C 的 C#/Java 开发人员。起初我认为“消息”只是方法调用的不同名称,所以:
[person jumpInTheAir];
只是用于编写的 Objective C 语法
person.jumpInTheAir();
但现在我已经阅读了 here和 here以及其他各种地方,这些概念实际上并不相同,并且可以具有不同的行为/优势。但是,我仍然不确定为什么语言设计者会选择一个消息传递系统,而不是像 C# 和 Java 中那样更直接的方法调用系统。
消息给Objective C编程语言带来了哪些优势?
最佳答案
At first I assumed "messages" were just a different name for method calls,
是也不是。 “消息”是方法调用的 Smalltalk 和 Objective-C 术语。问题是,不仅术语不同,实际实现也不同。有 8 种不同的可能组合来匹配术语、语法和实现,如下所示:
+-------------------+----------------------+--------------------+
| terminology | syntax | implementation |
+-------------------+----------------------+--------------------+
| "method call" | Simula (o.method()) | static binding | non-virtual C++ methods
+-------------------+----------------------+--------------------+
| "method call" | Simula | dynamic binding |
+-------------------+----------------------+--------------------+
| "method call" | Smalltalk ([o meth]) | static binding |
+-------------------+----------------------+--------------------+
| "method call" | Smalltalk | dynamic binding |
+-------------------+----------------------+--------------------+
| "message passing" | Simula | static binding |
+-------------------+----------------------+--------------------+
| "message passing" | Simula | dynamic binding |
+-------------------+----------------------+--------------------+
| "message passing" | Smalltalk | static binding |
+-------------------+----------------------+--------------------+
| "message passing" | Smalltalk | dynamic binding | Objective-C
+-------------------+----------------------+--------------------+
语言设计者选择的组合只是一个品味问题。
I'm still uncertain why the language designers would choose a messaging system over a more direct method calling system
因为它有一些优点,比如运行时干预和内省(introspection)——可以在运行时查询和修改类、方法和对象的行为。在 Objective-C 的实现中,这样做的方式非常便宜,几乎没有开销。
关于objective-c - Objective C 中的消息与 C# 和 Java 中的简单方法调用相比有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18944800/