不知道的sizeof()的结构。为什么? [英] sizeof() structures not known. Why?

查看:264
本文介绍了不知道的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'没有一个predefined大小,因此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.

是如何浮动和短期不会编译时间常数? 8 - /

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

推荐答案

浮动是大小恒 - 但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:

有关某些predefined类型,在 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.

请注意,您的可以的使用的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天全站免登陆