为什么未装箱类型有方法?
为什么你可以做类似
int i = 10;
i.ToString();
'c'.Equals('d');
1.ToString();
true.GetType();
C# 的事情?这些东西要么是原始的、字面的、未装箱的,要么是这些东西的任意组合;那么为什么他们有方法呢? 它们不是对象,因此不应该有方法。这个语法糖还有其他用途吗?如果是这样,那又怎样?例如,我可以理解拥有执行这些操作的函数:
string ToString(int number)
{
// Do mad code
return newString;
}
但在这种情况下,您会将其称为函数,而不是方法:
string ranch = ToString(1);
这里发生了什么?
编辑:
刚刚意识到 C# 不再是 java 的克隆,并且规则完全不同。哎呀:P
Why can you do things like
int i = 10;
i.ToString();
'c'.Equals('d');
1.ToString();
true.GetType();
in C#? Those things right there are either primitive, literal, unboxed, or any combination of those things; so why do they have methods? They are not objects and so should not have methods. Is this syntax sugar for something else? If so, what? I can understand having functions that do these things, for example:
string ToString(int number)
{
// Do mad code
return newString;
}
but in that case you would call it as a function, not a method:
string ranch = ToString(1);
What's going on here?
edit:
Just realised C# isn't a java clone anymore and the rules are totally different. oops :P
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
他们这样做是因为规范是这么说的(而且非常好):
...
...
正如规范所解释的,简单类型具有一些超能力,例如成为
const
的能力,一种可以用来代替 new 的特殊文字语法,以及计算的能力编译时间(2+2 实际上在最终的 MSIL 流中写为 4)但是方法(以及运算符)并不是特殊的超能力,所有结构都可以拥有它们。
该规范(对于 C# 4.0,我的复制粘贴来自早期版本)可以从 microsoft 网站下载: C# 语言规范 4.0
They act like that because the spec says so (and it's pretty nice) :
...
...
As the spec explains simple types have some super powers like the ability to be
const
, a special literal syntax that could be used instead of new, and the capacity to be computed at compilation time (2+2 is actually written as 4 in the final MSIL stream)But methods (as well as operators) aren't a special super powers and all structs could have them.
The specification (for C# 4.0, my copy paste is from an earlier version) could be downloaded from the microsoft website : C# Language Specification 4.0
Eric Lippert 最近的文章 继承和表示 对此进行了解释。(剧透:你是混淆继承和表示。)
不知道为什么你声称整数
i
、字符'c'
和整数1
是不是物体。他们是。Eric Lippert's recent article Inheritance and Representation explains.(Spoiler: You are confusing inheritance and representation.)
Not sure why you claim that the integer
i
, the character'c'
and the integer1
are not objects. They are.在 C# 中,所有基本类型实际上都是结构。
In C# all primitive types are actually structures.
这样您就可以使用它们了!
能够这样做很方便,所以你也可以。
现在,为了做到这一点,可以将基元视为结构。例如,32 位整数可以作为 32 位整数处理,但也可以作为
public struct Int32 : IComparable、IFormattable、IConvertible、IComparable、IEquatable
处理。我们基本上可以两全其美。So that you can use them!
It's convenient to be able to do so, so you can.
Now, in order to do so, primitives can be treated as structs. E.g. a 32-bit integer can be processed as a 32-bit integer, but it can also be processed as
public struct Int32 : IComparable, IFormattable, IConvertible, IComparable<int>, IEquatable<int>
. We mostly get the best of both worlds.