在c#中,int和Int32是同一个东西,但我读过很多次int比Int32更受欢迎,没有给出原因。这是有原因的吗,我应该在意吗?
当前回答
我知道最好的做法是使用int,所有MSDN代码都使用int。然而,据我所知,除了标准化和一致性之外,没有其他原因。
其他回答
根据Visual Studio 2012中的即时窗口,Int32是int型,Int64是long型。输出如下:
sizeof(int)
4
sizeof(Int32)
4
sizeof(Int64)
8
Int32
int
base {System.ValueType}: System.ValueType
MaxValue: 2147483647
MinValue: -2147483648
Int64
long
base {System.ValueType}: System.ValueType
MaxValue: 9223372036854775807
MinValue: -9223372036854775808
int
int
base {System.ValueType}: System.ValueType
MaxValue: 2147483647
MinValue: -2147483648
int是c#语言中System的快捷方式。Int32
虽然这确实意味着微软可能会改变这种映射,但FogCreek讨论的一篇文章指出[来源]
“关于64位的问题——微软确实在开发64位版本的。net框架,但我很确定int不会在该系统上映射到64位。
原因:
1. c# ECMA标准明确规定int是32位,long是64位。
2. 微软在框架1.1版本中引入了额外的属性和方法,返回长值而不是int值,例如Array。除了Array.GetLength之外的GetLongLength。
所以我认为可以肯定地说,所有内置的c#类型都将保持当前的映射。”
ECMA-334:2006 c#语言规范(p18)
每个预定义类型都是系统提供类型的简写。例如,关键字int指向结构体System.Int32。就风格而言,使用关键字优于使用完整的系统类型名。
虽然它们(大部分)是相同的(参见下面的一个[错误]差异),但您绝对应该注意并应该使用Int32。
The name for a 16-bit integer is Int16. For a 64 bit integer it's Int64, and for a 32-bit integer the intuitive choice is: int or Int32? The question of the size of a variable of type Int16, Int32, or Int64 is self-referencing, but the question of the size of a variable of type int is a perfectly valid question and questions, no matter how trivial, are distracting, lead to confusion, waste time, hinder discussion, etc. (the fact this question exists proves the point). Using Int32 promotes that the developer is conscious of their choice of type. How big is an int again? Oh yeah, 32. The likelihood that the size of the type will actually be considered is greater when the size is included in the name. Using Int32 also promotes knowledge of the other choices. When people aren't forced to at least recognize there are alternatives it become far too easy for int to become "THE integer type". The class within the framework intended to interact with 32-bit integers is named Int32. Once again, which is: more intuitive, less confusing, lacks an (unnecessary) translation (not a translation in the system, but in the mind of the developer), etc. int lMax = Int32.MaxValue or Int32 lMax = Int32.MaxValue? int isn't a keyword in all .NET languages. Although there are arguments why it's not likely to ever change, int may not always be an Int32.
缺点是要多输入两个字符和[bug]。
这不会编译
public enum MyEnum : Int32
{
AEnum = 0
}
但这将:
public enum MyEnum : int
{
AEnum = 0
}
没关系。int是语言关键字,Int32是实际的系统类型。
也可以在这里看到我对相关问题的回答。
推荐文章
- 如何强制LINQ Sum()返回0而源集合是空的
- 将值附加到查询字符串
- Selenium c# WebDriver:等待元素出现
- 我如何添加双引号的字符串,是在一个变量?
- 检查字符串是否包含字符串列表中的元素
- 最好的方法在asp.net强制https为整个网站?
- 将字符串转换为System.IO.Stream
- 我如何检查如果一个变量是JavaScript字符串?
- 如何从枚举中选择一个随机值?
- 驻留在App_Code中的类不可访问
- 在链式LINQ扩展方法调用中等价于'let'关键字的代码
- dynamic (c# 4)和var之间的区别是什么?
- Visual Studio: ContextSwitchDeadlock
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头