在c#中,int和Int32是同一个东西,但我读过很多次int比Int32更受欢迎,没有给出原因。这是有原因的吗,我应该在意吗?
当前回答
我总是使用系统类型——例如,Int32而不是int。我在阅读了Applied . net Framework Programming之后采用了这种做法——作者Jeffrey Richter为使用完整类型名做了一个很好的例子。以下两点让我印象深刻:
Type names can vary between .NET languages. For example, in C#, long maps to System.Int64 while in C++ with managed extensions, long maps to Int32. Since languages can be mixed-and-matched while using .NET, you can be sure that using the explicit class name will always be clearer, no matter the reader's preferred language. Many framework methods have type names as part of their method names: BinaryReader br = new BinaryReader( /* ... */ ); float val = br.ReadSingle(); // OK, but it looks a little odd... Single val = br.ReadSingle(); // OK, and is easier to read
其他回答
曾经,int数据类型与编译器目标机器的寄存器大小挂钩。例如,16位系统的编译器将使用16位整数。
然而,谢天谢地,我们已经很少看到16位了,当64位开始流行时,人们更关心的是使它与旧软件兼容,32位已经存在了很长时间,对于大多数编译器来说,int只是假设为32位。
我总是在定义变量时使用别名类型(int, string等),在访问静态方法时使用真实名称:
int x, y;
...
String.Format ("{0}x{1}", x, y);
看到像int.TryParse()这样的东西似乎很难看。除了风格,我这么做没有别的原因。
如前所述,int = Int32。为了安全起见,请确保始终使用int. minvalue /int。MaxValue在实现任何关心数据类型边界的东西时。假设. net决定int现在是Int64,那么你的代码就不那么依赖于边界了。
使用Int32类型需要对System或完全限定(System.Int32)的命名空间引用。我倾向于int,因为它不需要名称空间导入,因此在某些情况下减少了名称空间冲突的机会。当编译为IL时,两者之间没有区别。
根据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
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和