sizeof运算符

sizeof运算符

用于获取非托管类型的大小(以字节为单位)。 非托管类型包括下表列出的内置类型以及以下类型:

枚举类型
指针类型
用户定义的结构,不包含任何属于引用类型的字段或属性
下面的示例演示如何检索 int 的大小:
C#
// Constant value 4:
int intSize = sizeof(int);

备注
从 C# 2.0 版开始,将 sizeof 应用于内置类型不再要求使用 unsafe 模式。
不能重载 sizeof 运算符。 sizeof 运算符的返回值是 int 类型。 下表列出了一些常量值,这些值对应于以某些内置类型为操作数的 sizeof 表达式。

表达式

常量值

sizeof(sbyte)

1

sizeof(byte)

1

sizeof(short)

2

sizeof(ushort)

2

sizeof(int)

4

sizeof(uint)

4

sizeof(long)

8

sizeof(ulong)

8

sizeof(char)

2 (Unicode)

sizeof(float)

4

sizeof(double)

8

sizeof(decimal)

16

sizeof(bool)

1

对于所有其他类型(包括结构),sizeof 运算符只能在不安全代码块中使用。 尽管可以使用 Marshal.SizeOf 方法,但此方法返回的值并不总是与 sizeof 返


对于所有其他类型(包括结构),sizeof 运算符只能在不安全代码块中使用。 尽管可以使用 Marshal.SizeOf 方法,但此方法返回的值并不总是与 sizeof 返回的值相同。 Marshal.SizeOf 在封送类型后返回大小,而 sizeof 返回公共语言运行时分配的大小(包括所有填充)。
示例
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UseSizeof
{
class Program
{
static void Main(string[] args)
{
//Sizeof运算符
Console.WriteLine("The size of byte is ({0})个字节", sizeof(byte));
Console.WriteLine("The size of sbyte is ({0})个字节", sizeof(sbyte));
Console.WriteLine("The size of short is ({0})个字节", sizeof(short));
Console.WriteLine("The size of ushort is ({0})个字节", sizeof(ushort));
Console.WriteLine("The size of int is ({0})个字节", sizeof(int));
Console.WriteLine("The size of uint is ({0})个字节", sizeof(uint));
Console.WriteLine("The size of long is ({0})个字节", sizeof(long));
Console.WriteLine("The size of ulong is ({0})个字节", sizeof(ulong));
Console.WriteLine("The size of char is ({0})个字节", sizeof(char));
Console.WriteLine("The size of float is ({0})个字节", sizeof(float));
Console.WriteLine("The size of double is ({0})个字节", sizeof(double));
Console.WriteLine("The size of decimal is ({0})个字节", sizeof(decimal));
Console.WriteLine("The size of bool is ({0})个字节", sizeof(Boolean));
}
}
}


/*
Output:

The size of byte is (1)个字节
The size of sbyte is (1)个字节
The size of short is (2)个字节
The size of ushort is (2)个字节
The size of int is (4)个字节
The size of uint is (4)个字节
The size of long is (8)个字节
The size of ulong is (8)个字节
The size of char is (2)个字节
The size of float is (4)个字节
The size of double is (8)个字节
The size of decimal is (16)个字节
The size of bool is (1)个字节


*/

原文地址:https://www.cnblogs.com/melao2006/p/4238198.html