string = alias(String)
1.String和string再c#中的有什么不同?
2.datatype alias
1.String和string再c#中的有什么不同?
As others have noted, string
is an alias for System.String
. They compile to the same code, so at execution time there is no difference whatsoever. This is just one of the aliases in C#. The complete list is:
- object: System.Object
- string: System.String
- bool: System.Boolean
- byte: System.Byte
- sbyte: System.SByte
- short: System.Int16
- ushort: System.UInt16
- int: System.Int32
- uint: System.UInt32
- long: System.Int64
- ulong: System.UInt64
- float: System.Single
- double: System.Double
- decimal: System.Decimal
- char: System.Char
Apart from string
, object
, the aliases are all to value types. decimal
is a value type, but not a primitive type in the CLR. The only primitive type which doesn't have an alias is System.IntPtr
.
In the spec, the value type aliases are known as "simple types". Literals can be used for constant values of every simple type; no other value types have literal forms available. (Compare this with VB, which allows DateTime
literals, and has an alias for it too.)
There is one circumstance in which you have to use the aliases: when explicitly specifying an enum's underlying type. For instance:
public enum Foo : UInt32 {} // Invalid
public enum Bar : uint {} // Valid
Finally, when it comes to which to use: personally I use the aliases everywhere for the implementation, but the CLR type for any APIs. It really doesn't matter too much which you use in terms of implementation - consistency among your team is nice, but no-one else is going to care. On the other hand, it's genuinely important that if you refer to a type in an API, you do so in a language neutral way. A method called "ReadInt32" is unambiguous, whereas a method called "ReadInt" requires interpretation. The caller could be using a language which defines an "int" alias for Int16, for example. The .NET framework designers have followed this pattern, good examples being in the BitConverter, BinaryReader and Convert classes.
2.datatype alias
//C#:
using MyType = System.Int32; //define alias MyType for System.Int32
//Now we can use the alias MyType anywhere in our code instead of actual System.In32 like below
MyType myNumber=12;
Console.WriteLine(myNumber.ToString());
//If we want to change to System.Int64, We will simply change the alias, that’s it.
using MyType = System.Int64;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?