在c#中,int和Int32是同一个东西,但我读过很多次int比Int32更受欢迎,没有给出原因。这是有原因的吗,我应该在意吗?
当前回答
这在实践中没有什么区别,最终你会采用你自己的惯例。我倾向于在分配类型时使用关键字,在使用静态方法时使用类版本等:
int total = Int32.Parse("1009");
其他回答
前一段时间,我在微软做一个项目,当时微软。net CLR产品团队的人来拜访我们。这个人编写了例子,当他定义变量时,他使用“Int32”与“int”和“String”与“String”。
我记得在微软的其他示例代码中见过这种样式。所以,我做了一些研究,发现每个人都说“Int32”和“int”之间没有区别,除了语法着色。事实上,我发现很多材料都建议您使用“Int32”使您的代码更具可读性。所以,我采用了这种风格。
前几天我确实发现了不同!编译器不允许你使用" Int32 "输入enum,但当你使用" int "时,它允许你输入enum。别问我为什么,因为我还不知道。
例子:
public enum MyEnum : Int32
{
AEnum = 0
}
这个作品。
public enum MyEnum : int
{
AEnum = 0
}
取自:Int32符号vs. int
我使用int是为了防止Microsoft将整数的默认实现更改为一些新版本(我们称其为Int32b)。
然后,Microsoft可以将int别名更改为Int32b,我不需要更改任何代码就可以利用他们新的(希望是改进的)整数实现。
这同样适用于任何类型关键字。
我建议使用微软的StyleCop。
它类似于FxCop,但用于与样式相关的问题。默认配置与微软的内部样式指南相匹配,但也可以根据您的项目进行定制。
它可能需要一些时间来适应,但它肯定会使您的代码更好。
您可以将它包含在构建过程中,以自动检查是否违反。
根据我的经验,这是一种惯例。我不知道在Int32上使用int的任何技术原因,但它是:
打字更快。 对于典型的c#开发人员来说更加熟悉。 默认visual studio语法高亮显示的不同颜色。
我特别喜欢最后一个。:)
虽然它们(大部分)是相同的(参见下面的一个[错误]差异),但您绝对应该注意并应该使用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
}
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和