C# 中 object 与 Objective C 的等价物是什么?
在 c# 中,我可以声明 object o;
然后我可以分配 o=(float)5.0;
或 o="a string."
有吗Objective-C 的等价物?我尝试使用 id ,但它不采用浮点或整数等基本类型。谢谢你的帮助。
In c# I can declare object o;
then I can assign o=(float)5.0;
or o="a string."
Is there an equivalent for Objective-C? I tried to use id
but it does not take primitive type like float or integer. Thanks for helping.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Objective-C 并没有 CLR 所说的“统一类型系统”。换句话说,作为 C 的超集,Objective-C 的原始类型与对象实例完全不同。
id
类型可以存储对任何对象实例的引用(实际上是 OS X/iPhone Objective-C 运行时中的指针)。 C 的原始类型(例如int
、float
等)必须包裹在NSValue
或NSNumber
中才能赋值输入id
。当然,这正是 C# 编译器正在做的事情。只是在 C# 中,您不必显式执行装箱(拆箱)转换。很快,类似的代码
将成为第二天性,但不幸的是,按照现代标准来看,这些代码很冗长。
Objective-C doesn't have a "unified type system" in the words of the CLR. In other words, as a superset of C, Objective-C's primitive types are different beasts altogether than object instances. The
id
type can store references (really pointers in the OS X/iPhone Objective-C runtime) to any object instance. C's primitive types (e.g.int
,float
,etc.) must be wrapped inNSValue
orNSNumber
to be assigned to typeid
. Of course, this is exactly what the C# compiler is doing. It's just that in C#, you don't have to do the (un)boxing conversion explicitly.Pretty soon, code like
will become second nature, if unfortunately verbose by modern standards.
确实没有这样的事情。您可以使用
NSNumber
或NSValue
将本机数据类型作为对象处理。NSString
将处理字符串。您可以将所有这些分配给id
类型变量,但您需要使用正确的类的init
方法来创建它们。There isn't really such a thing. You can use
NSNumber
orNSValue
to handle native data types as objects.NSString
will do strings. You can assign all of those to anid
typed variable, but you'll need to create them with the correct class'sinit
methods.你是对的,
id
仅适用于 ObjC 对象引用。如果您想通过 id 引用来引用 int,则需要将其装箱到NSNumber
中。顺便说一句,C# 也对这些原语进行装箱,它只是自动执行。You are correct,
id
only works for ObjC object references. If you want to reference an int with an id reference, you need to box it into anNSNumber
. Incidentally, C# is boxing those primitives too, it's just doing it automatically.在我那个时代,我们必须在雪地里步行 15 英里,上坡,才能使用 空指针。哦,我们没有 StackOverflow!
Back in my day we had to walk 15 miles in the snow, uphill, to use void pointers. Oh, and we didn't have StackOverflow!
实际上,C# 数据类型只是其各自类的别名,这就是它们可以分配给对象类型的原因。
例如,int实际上是一个名为Int32的类。
正如@Barry 之前提到的,Objective-C 的情况并非如此。
Actually, C# data types are just aliases for their respective classes and that's why they can be assigned to object type.
For example, int is actually a class called Int32.
As @Barry mentioned earlier, that's not the case with Objective-C.