sizeof() 结构未知.为什么? [英] sizeof() structures not known. Why?

查看:29
本文介绍了sizeof() 结构未知.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能在简单的结构上使用 sizeof()?

Why can't I use sizeof() on simple structs?

例如:

private struct FloatShortPair
{
    public float myFloat;
    public short myShort;
};

int size = sizeof(FloatShortPair);  //CS0233

错误 CS0233:'FloatShortPair' 没有预定义的大小,因此 sizeof 只能在不安全的上下文中使用(考虑使用 System.Runtime.InteropServices.Marshal.SizeOf)

MSDN 声明:

sizeof 运算符只能用于编译时类型常数.如果您收到此错误,请确保标识符可以在编译时确定.如果不能,那么使用 SizeOf 而不是 sizeof.

The sizeof operator can only be used for types that are compile-time constants. If you are getting this error, make sure that the size of the identifier can be determined at compile time. If it cannot, then use SizeOf instead of sizeof.

float 和 short 不是编译时常量?8-/

How are float and short not compile time constants? 8-/

推荐答案

shortfloat 的大小是恒定的 - 但是 CLR 决定如何将浮动打包内存不一定一定是恒定的.例如,在 64 位处理器上,它可能决定在 8 字节边界上对齐每个值.

The sizes of short and float are constant - but how the CLR decided to pack that float in memory isn't necessarily constant. For example, on a 64-bit processor it may decide to align each value on an 8-byte boundary.

来自 C# 4 规范的第 18.5.8 节:

From the C# 4 spec, section 18.5.8:

对于某些预定义的类型,sizeof 运算符会产生一个常量值,如下表所示.

For certain predefined types, the sizeof operator yields a constant value as shown in the table below.

[...]

对于所有其他类型,sizeof 运算符的结果是实现定义的,并归类为值,而不是常量.

For all other types, the result of the sizeof operator is implementation-defined and is classified as a value, not a constant.

[...]

出于对齐的目的,结构的开头、结构内和结构的末尾可能会有未命名的填充.

For alignment purposes, there may be unnamed padding at the beginning of a struct, within a struct, and at the end of a struct.

请注意,在这种情况下,您可以unsafe 上下文中使用 sizeof.您应该使用它还是 Marshal.SizeOf 取决于您要做什么.

Note that you can use sizeof in this situation, within an unsafe context. Whether you should use that or Marshal.SizeOf depends on what you're trying to do.

这篇关于sizeof() 结构未知.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆