Objective-C 与 C# 相比如何?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1369078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:45:25  来源:igfitidea点击:

How does Objective-C compare to C#?

c#objective-c

提问by Alex Angas

I've recently purchased a Mac and use it primarily for C# development under VMWare Fusion. With all the nice Mac applications around I've started thinking about Xcode lurking just an install click away, and learning Objective-C.

我最近购买了一台 Mac,主要用于 VMWare Fusion 下的 C# 开发。有了周围所有漂亮的 Mac 应用程序,我开始考虑 Xcode 潜伏,只需点击一下安装,并学习 Objective-C。

The syntax between the two languages looks very different, presumably because Objective-C has its origins in C and C# has its origins in Java/C++. But different syntaxes can be learnt so that should be OK.

两种语言之间的语法看起来非常不同,大概是因为 Objective-C 起源于 C,而 C# 起源于 Java/C++。但是可以学习不同的语法,所以应该没问题。

My main concern is working with the language and if it will help to produce well-structured, readable and elegant code. I really enjoy features such as LINQ and var in C# and wonder if there are equivalents or better/different features in Objective-C.

我主要关心的是使用该语言,以及它是否有助于生成结构良好、可读且优雅的代码。我真的很喜欢 C# 中的 LINQ 和 var 等功能,想知道 Objective-C 中是否有等效的或更好/不同的功能。

What language features will I miss developing with Objective-C? What features will I gain?

我会怀念使用 Objective-C 开发的哪些语言特性?我将获得哪些功能?

Edit:The framework comparisons are useful and interesting but a languagecomparison are what this question is really asking (partly my fault for originally tagging with .net). Presumably both Cocoa and .NET are very rich frameworks in their own right and both have their purpose, one targeting Mac OS X and the other Windows.

编辑:框架比较有用且有趣,但语言比较才是这个问题真正要问的(部分是我最初用 标记的错.net)。据推测,Cocoa 和 .NET 本身都是非常丰富的框架,并且都有自己的目的,一个针对 Mac OS X,另一个针对 Windows。

Thank you for the well thought out and reasonably balanced viewpoints so far!

感谢您到目前为止经过深思熟虑和合理平衡的观点!

采纳答案by Quinn Taylor

No language is perfect for all tasks, and Objective-C is no exception, but there are some very specific niceties. Like using LINQand var(for which I'm not aware of a direct replacement), some of these are strictly language-related, and others are framework-related.

没有一种语言是适合所有任务的,Objective-C 也不例外,但有一些非常特殊的优点。就像使用LINQand var(我不知道可以直接替换)一样,其中一些与语言严格相关,而另一些则与框架相关。

(NOTE:Just as C# is tightly coupled with .NET, Objective-C is tightly coupled with Cocoa. Hence, some of my points may seem unrelated to Objective-C, but Objective-C without Cocoa is akin to C# without .NET / WPF / LINQ, running under Mono, etc. It's just not the way things are usually done.)

注意:正如 C# 与 .NET 紧密耦合一样,Objective-C 与 Cocoa 紧密耦合。因此,我的一些观点可能看起来与 Objective-C 无关,但没有 Cocoa 的 Objective-C 类似于没有 .NET 的 C# / WPF / LINQ,在 Mono 下运行等。这不是通常的做法。)

I won't pretend to fully elaborate the differences, pros, and cons, but here are some that jump to mind.

我不会假装完全阐述差异、优点和缺点,但这里有一些我会想到的。

  • One of the best parts of Objective-C is the dynamic nature — rather than calling methods, you send messages, which the runtime routes dynamically. Combined (judiciously) with dynamic typing, this can make a lot of powerful patterns simpler or even trivial to implement.

  • As a strict superset of C, Objective-C trusts that you know what you're doing. Unlike the managed and/or typesafe approach of languages like C# and Java, Objective-C lets you do what you want and experience the consequences. Obviously this can be dangerous at times, but the fact that the language doesn't actively prevent you from doing most things is quite powerful. (EDIT:I should clarify that C# also has "unsafe" features and functionality, but they default behavior is managed code, which you have to explicitly opt out of. By comparison, Java onlyallows for typesafe code, and never exposes raw pointers in the way that C and others do.)

  • Categories (adding/modifying methods on a class without subclassing or having access to source) is an awesome double-edged sword. It can vastly simplify inheritance hierarchies and eliminate code, but if you do something strange, the results can sometimes be baffling.

  • Cocoa makes creating GUI apps much simpler in many ways, but you do have to wrap your head around the paradigm. MVC design is pervasive in Cocoa, and patterns such as delegates, notifications, and multi-threaded GUI apps are well-suited to Objective-C.

  • Cocoa bindings and key-value observing can eliminate tons of glue code, and the Cocoa frameworks leverage this extensively. Objective-C's dynamic dispatch works hand-in-hand with this, so the type of the object doesn't matter as long as it's key-value compliant.

  • You will likely miss generics and namespaces, and they have their benefits, but in the Objective-C mindset and paradigm, they would be niceties rather than necessities. (Generics are all about type safety and avoiding casting, but dynamic typing in Objective-C makes this essentially a non-issue. Namespaces would be nice if done well, but it's simple enough to avoid conflicts that the cost arguably outweighs the benefits, especially for legacy code.)

  • For concurrency, Blocks (a new language feature in Snow Leopard, and implemented in scores of Cocoa APIs) are extremely useful. A few lines (frequently coupled with Grand Central Dispatch, which is part of libsystem on 10.6) can eliminates significant boilerplate of callback functions, context, etc. (Blocks can also be used in C and C++, and could certainly be added to C#, which would be awesome.) NSOperationQueue is also a very convenient way to add concurrency to your own code, by dispatching either custom NSOperation subclasses or anonymous blocks which GCD automatically executes on one or more different threads for you.

  • Objective-C 最好的部分之一是动态特性——而不是调用方法,你发送消息,运行时动态路由。结合(明智地)动态类型,这可以使许多强大的模式更容易实现,甚至微不足道。

  • 作为 C 的严格超集,Objective-C 相信您知道自己在做什么。与 C# 和 Java 等语言的托管和/或类型安全方法不同,Objective-C 让您可以随心所欲并体验结果。显然,这有时可能很危险,但该语言不会主动阻止您做大多数事情这一事实非常强大。(编辑:我应该澄清一下 C# 也有“不安全”的特性和功能,但它们的默认行为是托管代码,你必须明确选择退出。相比之下,Java允许类型安全代码,并且从不公开原始指针C 和其他人的方式。)

  • 类别(在没有子类化或访问源的情况下在类上添加/修改方法)是一把很棒的双刃剑。它可以极大地简化继承层次结构并消除代码,但是如果你做了一些奇怪的事情,结果有时会令人费解。

  • Cocoa 在许多方面使创建 GUI 应用程序变得更加简单,但您必须围绕范例进行思考。MVC 设计在 Cocoa 中无处不在,委托、通知和多线程 GUI 应用程序等模式非常适合 Objective-C。

  • Cocoa 绑定和键值观察可以消除大量的胶水代码,而 Cocoa 框架广泛地利用了这一点。Objective-C 的动态分派与此密切相关,因此对象的类型并不重要,只要它符合键值对即可。

  • 您可能会错过泛型和命名空间,它们有它们的好处,但在 Objective-C 的思维方式和范式中,它们只是细节而不是必需品。(泛型都是关于类型安全和避免强制转换的,但是 Objective-C 中的动态类型使得这基本上不是问题。如果做得好,命名空间会很好,但它很简单,可以避免成本超过收益的冲突,尤其是用于遗留代码。)

  • 对于并发性,块(Snow Leopard 中的一种新语言功能,并在许多 Cocoa API 中实现)非常有用。几行代码(经常与 Grand Central Dispatch 结合,它是 10.6 上的 libsystem 的一部分)可以消除重要的回调函数、上下文等样板。(块也可以在 C 和 C++ 中使用,当然可以添加到 C#,这太棒了。) NSOperationQueue 也是一种向您自己的代码添加并发性的非常方便的方法,通过分派自定义 NSOperation 子类或匿名块,GCD 会自动在一个或多个不同线程上为您执行。

回答by jonnii

One thing I love about objective-c is that the object system is based on messages, it lets you do really nice things you couldn't do in C# (at least not until they support the dynamic keyword!).

我喜欢objective-c的一件事是对象系统基于消息,它可以让你做在C#中无法做的非常好的事情(至少在它们支持dynamic关键字之前不会!)。

Another great thing about writing cocoa apps is Interface Builder, it's a lot nicer than the forms designer in Visual Studio.

编写可可应用程序的另一个好处是 Interface Builder,它比 Visual Studio 中的表单设计器要好得多。

The things about obj-c that annoy me (as a C# developer) are the fact that you have to manage your own memory (there's garbage collection, but that doesn't work on the iPhone) and that it can be very verbose because of the selector syntax and all the [ ].

使我(作为 C# 开发人员)烦恼的关于 obj-c 的事情是您必须管理自己的内存(有垃圾收集,但在 iPhone 上不起作用)并且它可能非常冗长,因为选择器语法和所有 [ ]。

回答by jonnii

The method calls used in obj-c make for easily read code, in my opinion much more elegant than c# and obj-c is built on top of c so all c code should work fine in obj-c. The big seller for me though is that obj-c is an open standard so you can find compilers for any system.

obj-c 中使用的方法调用使代码易于阅读,在我看来,它比 c# 优雅得多,而且 obj-c 构建在 c 之上,因此所有 c 代码都应该在 obj-c 中正常工作。不过对我来说,最大的卖点是 obj-c 是一个开放标准,因此您可以找到适用于任何系统的编译器。

回答by Cinder6

Here's a pretty good article comparing the two languages: http://www.coderetard.com/2008/03/16/c-vs-objective-c/

这是一篇比较两种语言的非常好的文章:http: //www.coderetard.com/2008/03/16/c-vs-objective-c/

回答by TimothyP

No technical review here, but I just find Objective-C much less readable. Given the example Cinder6 gave you:

这里没有技术评论,但我发现 Objective-C 的可读性要差得多。鉴于 Cinder6 给你的例子:

C#

C#

List<string> strings = new List<string>();
strings.Add("xyzzy");                  // takes only strings
strings.Add(15);                       // compiler error
string x = strings[0];                 // guaranteed to be a string
strings.RemoveAt(0);                   // or non-existant (yielding an exception)

Objective-C

目标-C

NSMutableArray *strings = [NSMutableArray array];
[strings addObject:@"xyzzy"];
[strings addObject:@15];
NSString *x = strings[0];
[strings removeObjectAtIndex:0];

It looks awful. I even tried reading 2 books on it, they lost me early on, and normally I don't get that with programming books / languages.

它看起来很糟糕。我什至尝试阅读有关它的 2 本书,他们很早就失去了我,通常我不会通过编程书籍/语言来理解。

I'm glad we have Mono for Mac OS, because if I'd had to rely on Apple to give me a good development environment...

我很高兴我们有适用于 Mac OS 的 Mono,因为如果我不得不依赖 Apple 给我一个良好的开发环境......

回答by DSO

Probably most important difference is memory management. With C# you get garbage collection, by virtue of it being a CLR based language. With Objective-C you need to manage memory yourself.

可能最重要的区别是内存管理。使用 C#,您可以获得垃圾收集,因为它是一种基于 CLR 的语言。使用 Objective-C,您需要自己管理内存。

If you're coming from a C# background (or any modern language for that matter), moving to a language without automatic memory management will be really painful, as you will spend a lot of your coding time on properly managing memory (and debugging as well).

如果您来自 C# 背景(或任何现代语言),迁移到没有自动内存管理的语言将非常痛苦,因为您将花费大量编码时间来正确管理内存(和调试好)。

回答by alesplin

Other than the paradigm difference between the 2 languages, there's not a lot of difference. As much as I hate to say it, you can do the same kind of things (probably not as easily) with .NET and C# as you can with Objective-C and Cocoa. As of Leopard, Objective-C 2.0 has garbage collection, so you don't haveto manage memory yourself unless you want to (code compatibility with older Macs and iPhone apps are 2 reasons to want to).

除了两种语言之间的范式差异外,没有太大区别。尽管我不想这么说,但您可以使用 .NET 和 C# 做与使用 Objective-C 和 Cocoa 一样的事情(可能不会那么容易)。作为豹,Objective-C的2.0有垃圾收集,所以你不要,除非你想(代码兼容旧的Mac和iPhone的应用程序都需要2个原因)自己管理内存。

As far as structured, readable code is concerned, much of the burden there lies with the programmer, as with any other language. However, I find that the message passing paradigm lends itself well to readable code provided you name your functions/methods appropriately (again, just like any other language).

就结构化、可读的代码而言,与任何其他语言一样,程序员的大部分负担都在。但是,我发现消息传递范式非常适合可读代码,前提是您适当地命名函数/方法(同样,就像任何其他语言一样)。

I'll be the first to admit that I'm not very familiar with C# or .NET. But the reasons Quinn listed above are quite a few reasons that I don't care to become so.

我将首先承认我对 C# 或 .NET 不是很熟悉。但是上面列出的奎因的原因很多,我不想变成这样。

回答by PeyloW

Manual memory management is something beginners to Objective-C seems to have most problem with, mostly because they think it is more complex than it is.

手动内存管理似乎是 Objective-C 初学者遇到的最大问题,主要是因为他们认为它比实际更复杂。

Objective-C and Cocoa by extension relies on conventions over enforcement; know and follow a very small set of rules and you get a lot for free by the dynamic run-time in return.

通过扩展,Objective-C 和 Cocoa 依赖于约定而不是强制执行;知道并遵循一组非常小的规则,作为回报,您可以通过动态运行时免费获得很多。

The not 100% true rule, but good enough for everyday is:

不是 100% 真实的规则,但足够日常使用的是:

  • Every call to allocshould be matched with a releaseat the end of the current scope.
  • If the return value for your method has been obtained by allocthen it should be returned by return [value autorelease];instead of being matched by a release.
  • Use properties, and there is no rule three.
  • 每次调用alloc都应与release当前作用域末尾的a 匹配。
  • 如果你的方法的返回值已经被获取,alloc那么它应该被返回return [value autorelease];而不是被匹配release
  • 使用属性,没有规则三。

The longer explanation follows.

更长的解释如下。

Memory management is based on ownership; onlythe owner of an object instance should ever release the object, everybodyelse should always do nothing. This mean that in 95% of all code you treat Objective-C as if it was garbage collected.

内存管理基于所有权;只有对象实例的所有者应该释放该对象,其他所有人都应该始终不做任何事情。这意味着在 95% 的代码中,您将 Objective-C 视为垃圾收集。

So what about the other 5%? You have three methods to look out for, any object instance received from these method are owned by the current method scope:

那么剩下的 5% 呢?您需要注意三个方法,从这些方法接收到的任何对象实例都归当前方法范围所有

  • alloc
  • Any method beginning with the word new, such as newor newService.
  • Any method containing the word copy, such as copyand mutableCopy.
  • alloc
  • 任何以new开头的方法,例如newor newService
  • 任何包含单词 copy 的方法,例如copyand mutableCopy

The method have three possible options as of what to do with it's owned object instances before it exits:

该方法有三个可能的选项,即在退出之前如何处理它拥有的对象实例:

  • Release it using releaseif it is no longer needed.
  • Give ownership to the a field (instance variable), or a global variable by simply assigning it.
  • Relinquish ownership but give someone else a chance to take ownership before the instance goes away by calling autorelease.
  • release如果不再需要,请使用释放它。
  • 通过简单地分配给a 字段(实例变量)或全局变量的所有权。
  • 放弃所有权但让其他人有机会在实例消失之前通过调用autorelease.

So when should you pro-actively take ownership by calling retain? Two cases:

那么什么时候你应该通过调用主动获取所有权retain?两种情况:

  • When assigning fields in your initializers.
  • When manually implementing setter method.
  • 在初始值设定项中分配字段时。
  • 手动实现 setter 方法时。

回答by brentlightsey

As a programmer just getting started with Objective-C for iPhone, coming from C# 4.0, I'm missing lambda expressions, and in particular, Linq-to-XML. The lambda expressions are C#-specific, while the Linq-to-XML is really more of a .NET vs. Cocoa contrast. In a sample app I was writing, I had some XML in a string. I wanted to parse the elements of that XML into a collection of objects.

作为一名刚开始使用 Objective-C for iPhone(来自 C# 4.0)的程序员,我缺少 lambda 表达式,尤其是 Linq-to-XML。lambda 表达式是特定于 C# 的,而 Linq-to-XML 实际上更像是 .NET 与 Cocoa 的对比。在我编写的示例应用程序中,我在字符串中包含了一些 XML。我想将该 XML 的元素解析为一个对象集合。

To accomplish this in Objective-C/Cocoa, I had to use the NSXmlParser class. This class relies on another object which implements the NSXMLParserDelegateprotocol with methods that are called (read: messages sent) when an element open tag is read, when some data is read (usually inside the element), and when some element end tag is read. You have to keep track of the parsing status and state. And I honestly have no idea what happens if the XML is invalid. It's great for getting down to the details and optimize performance, but oh man, that's a whole lot of code.

为了在 Objective-C/Cocoa 中实现这一点,我必须使用NSXmlParser 类。此类依赖于另一个对象,该对象实现了NSXMLParserDelegate协议,其方法在读取元素打开标记、读取某些数据(通常在元素内部)以及读取某些元素结束标记时调用(读取:发送的消息) . 您必须跟踪解析状态和状态。老实说,我不知道如果 XML 无效会发生什么。这对于深入了解细节和优化性能非常有用,但是天哪,那是一大堆代码。

By contrast, here's the code in C#:

相比之下,这是 C# 中的代码:

using System.Linq.Xml;
XDocument doc = XDocument.Load(xmlString);
IEnumerable<MyCustomObject> objects = doc.Descendants().Select(
         d => new MyCustomObject{ Name = d.Value});

And that's it, you've got a collection of custom objects drawn from XML. If you wanted to filter those elements by value, or only to those that contain a specific attribute, or if you just wanted the first 5, or to skip the first 1 and get the next 3, or just find out if any elements were returned... BAM, all right there in the same line of code.

就是这样,您已经获得了一组从 XML 中提取的自定义对象。如果你想按值过滤这些元素,或者只过滤那些包含特定属性的元素,或者如果你只想要前 5 个,或者跳过前 1 个并获取接下来的 3 个,或者只是找出是否有任何元素被返回... BAM,就在同一行代码中。

There are many open-source classes that make this processing a lot easier in Objective-C, so that does much of the heavy lifting. It's just not this built in.

有许多开源类使 Objective-C 中的处理变得更加容易,因此可以完成大部分繁重的工作。这不是内置的。

*NOTE: I didn't actually compile the code above, it's just meant as an example to illustrate the relative lack of verbosity required by C#.

*注意:我实际上并没有编译上面的代码,它只是作为一个例子来说明 C# 所需的相对缺乏冗长。

回答by Waz

I've been programming in C, C++ and C# now for over 20 years, first started in 1990. I have just decided to have a look at the iPhone development and Xcode and Objective-C. Oh my goodness... all the complaints about Microsoft I take back, I realise now how bad things code have been. Objective-C is over complex compared to what C# does. I have been spoilt with C# and now I appreciate all the hard work Microsoft have put in. Just reading Objective-C with method invokes is difficult to read. C# is elegant in this. That is just my opinion, I hoped that the Apple development language was a good as the Apple products, but dear me, they have a lot to learn from Microsoft. There is no question C#.NET application I can get an application up and running many times faster than XCode Objective-C. Apple should certainly take a leaf out of Microsoft's book here and then we'd have the perfect environment. :-)

我已经用 C、C++ 和 C# 编程了 20 多年,第一次开始于 1990 年。我刚刚决定看看 iPhone 开发以及 Xcode 和 Objective-C。哦,天哪……我收回了所有关于微软的抱怨,我现在意识到代码是多么糟糕。与 C# 相比,Objective-C 过于复杂。我已经被 C# 宠坏了,现在我感谢微软付出的所有努力。仅仅阅读带有方法调用的 Objective-C 是很难阅读的。C#在这方面很优雅。这只是我的看法,我希望苹果的开发语言能像苹果的产品一样好,但是亲爱的,他们有很多东西要向微软学习。毫无疑问,C#.NET 应用程序我可以比 XCode Objective-C 快很多倍地启动和运行应用程序。苹果当然应该在这里学习微软的书,然后我们就会拥有完美的环境。:-)