跳转至

数据类型⚓︎

一、内置值类型⚓︎

C#类型 名称 内存大小 范围 默认值 .Net类型
byte 8位无符号整数 8 bit 0-255 0 System.Byte
short 16位有符号短整型 16 bit -2^15 ~ 2^15-1 0 System.Int16
int 32位有符号整数 32 bit -2^31 ~ 2^31-1 0 System.Int32
long 64位有符号整数 64 bit -2^63 ~ 2^63-1 0L System.Int64
float 单精度浮点型 32 bit 6-9位数字 0.0F System.Single
double 双精度浮点型 64 bit 15-17位数字 0.0D System.Double
decimal 十进制数 128 bit 28-29位数字 0.0M System.Decimal
bool 布尔类型 - true、false false System.Boolean
char 字符类型 16 bit U+0000 ~ U+FFFF '\0' System.Char

Note

上述为常见内置值类型,除此之外还有 sbyte(有符号)、ushort(无符号短整型)、uint(无符号整型)、ulong(无符号长整型)等,更多可参考 值类型 - C# 参考 | Microsoft Learn

二、内置引用类型⚓︎

C#类型 名称 .Net类型
object 对象类型 System.Object
string 字符串类型 System.String
dynamic 动态类型 System.Dynamic

三、指针类型⚓︎

指针类型变量用来存储一个变量的地址,声明指针的语句:type* identifier

char* cptr; // 字符指针
int* iptr; // 整型指针

四、变量与常量⚓︎

01 变量⚓︎

变量:程序执行期间可以被改变的量,需要相应的内存存储。

变量声明:

string a = "hello, world";                  // hello, world
string b = @"hello, world";               // hello, world
string c = "hello \t world";               // hello     world
string d = @"hello \t world";               // hello \t world

可推断类型变量:

var e = "hello var";

02 常量⚓︎

常量:通过const关键字定义常量,在声明时必须初始化,在编译时设置其值并且不能更改其值的量。

示例:

class Calendar
{
    public const int Months = 12;
    public const int Weeks = 52, Days = 365;// 可同时定义多个
}

如果不创建循环引用,则用于初始化常量的表达式可以引用另一个常量:

引用常量
class Calendar
{
    public const int Months = 12;
    public const int Weeks = 52;
    public const int Days = 365;
    // 可以引用已定义的常量
    public const double DaysPerWeek = (double) Days / (double) Weeks;
    public const double DaysPerMonth = (double) Days / (double) Months;
}

外部访问常量通过类名的方式进行:

常量访问
int birthstones = Calendar.Months;

Danger

引用其他代码(如 DLL)中定义的常量值时要格外小心。 如果新版本的 DLL 定义了新的常量值,则程序仍将保留旧的文本值,直到根据新版本重新编译。

五、类型转换⚓︎

01 隐式类型转换⚓︎

C# 默认的以安全方式进行的转换, 不会导致数据丢失。可以进行隐式类型转换的类型有:

  • 小整型转大整型,如 short -> intint->long
  • 派生类转基类

02 显示类型转换⚓︎

即强制类型转换,显式转换需要强制转换运算符(),而且强制转换可能会造成数据丢失。

  • 大整型转小整型,如 int i = (int) 12.3;
  • 不同引用类型的转换等,如 Person p = (Person)human;

03 类型转换方法⚓︎

方法 作用
ToString 将类型转换为字符串类型
ToBoolean 将类型转换为布尔类型
ToInt16 将类型转换为16位整型
ToType 将类型转换为指定类型
ToXXX 类推,不再赘述

六、类型可空⚓︎

01 ?运算符⚓︎

int? 表示类型变量可以为 null

02 ??运算符⚓︎

七、装箱拆箱(待完成)⚓︎

01 装箱⚓︎

02 拆箱⚓︎