答案是C#的sizeof运算符用于获取非托管类型在编译时的内存大小,支持基本数据类型、枚举和仅含非托管字段的结构体,但不支持引用类型。

C#的
sizeof
sizeof
要使用
sizeof
unsafe
unsafe
语法非常直接:
sizeof(TypeName)
TypeName
using System;
public unsafe class MemoryExamples
{
public static void Main(string[] args)
{
Console.WriteLine($"int 类型大小: {sizeof(int)} 字节");
Console.WriteLine($"double 类型大小: {sizeof(double)} 字节");
Console.WriteLine($"bool 类型大小: {sizeof(bool)} 字节"); // 通常是1字节
Console.WriteLine($"char 类型大小: {sizeof(char)} 字节"); // 2字节,UTF-16
Console.WriteLine($"long 类型大小: {sizeof(long)} 字节");
// 结构体示例
MyStruct s = new MyStruct();
Console.WriteLine($"MyStruct 类型大小: {sizeof(MyStruct)} 字节");
// 指针类型大小取决于平台(32位或64位)
Console.WriteLine($"int* 类型大小: {sizeof(int*)} 字节");
Console.WriteLine($"void* 类型大小: {sizeof(void*)} 字节");
// 尝试获取引用类型的大小会报错
// Console.WriteLine($"string 类型大小: {sizeof(string)} 字节"); // 编译错误
}
// 一个简单的非托管结构体
public struct MyStruct
{
public int A;
public byte B;
public short C;
}
}从上面的例子可以看出,
sizeof
string
sizeof
sizeof
sizeof
**具体支持的类型包括:
以上就是C#的sizeof运算符怎么获取类型大小?支持哪些类型?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号