gpt4 book ai didi

objective-c - 为什么 Objective-C 对消息使用方括号?

转载 作者:太空狗 更新时间:2023-10-30 03:18:04 26 4
gpt4 key购买 nike

我正在读一本关于 Smalltalk 的书(Charmond Liu's Smalltalk, Objects and Design)。他以 HomeBudget 对象作为如何发送带有多个参数的单个消息的示例,讲述了 Smalltalk 中消息的工作方式:

HomeBudget spend: 229 on: 'VCR'

Objective-C 使用了很多来自 Smalltalk 的想法,例如消息传递对象和参数的冒号,但始终将消息发送包含在方括号中。相同的调用将是:

[homeBudget spend:229 on:@"VCR"];

为什么 Objective-C 使用方括号(而不是像 Smalltalk 那样让消息空空如也)?因为它是基于 C 的,所以它需要语法吗?这是一种风格选择吗?它是否为您可以表达的内容提供了更多选择?还有别的原因吗?

最佳答案

我找到了 an interview with Brad Cox这似乎暗示方括号用于语法:

DD: The square brackets are a distinctive part of Objective-C syntax. How did the square brackets come about and was this your doing?

BC: Yeah, that was me. Quite literally it was a search for something that wasn't taken. Curly braces were taken. Ordinary parentheses were taken. It was just a search for braces that wouldn't collide with something C used.

Tom Love 在 Masterminds of Programming 中也将方括号归功于自己,但他似乎在说这是一种风格选择:

I often refer to myself as the guy responsible for the square brackets in Objective-C, because Brad and I had a long conversation about. Do we have a C syntax that is consistently C, or do we create a hybrid language where I describe it as “the square bracket is a gear shift into the object land”? Our view was that if you had a hybrid language, you could build a set of foundation classes so that at some point most of the work is actually done inside the square brackets. This allows a lot of details to be hidden from a typical application programmer.

The square brackets are an indication of a message sent in Objective-C. The original idea was that once you built up a set of libraries of classes, then you’re going to spend most of your time actually operating inside the square brackets, so you’re really doing object-oriented programming using an underlying framework of objects that were developed in the hybrid language, which was a combination of procedural and object-oriented language. Then as you began to build up libraries of functionality, there’s less and less requirement to drop into the procedural world and you could stay within the square brackets. It was a deliberate decision to design a language that essentially had two levels— once you had built up enough capability, you could operate at the higher level. I actually think that’s one of the reasons. Had we chosen a very C-like syntax, I’m not sure anybody would know the name of the language anymore and it wouldn’t likely still be in use anywhere.

关于objective-c - 为什么 Objective-C 对消息使用方括号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23723838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com