C# 为什么未定义 sizeof(constant)

C# Why is the sizeof(constant) not defined

对不起,我刚刚写了一些东西来表达我的观点。

这是一个实际的示例代码:

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

namespace CacheScratch
{
    class Class1
    {
        public const int a = 0xABAC;

        int test()
        {
            return sizeof(a);
        }
    }
}

如果我有一个常量,为什么我会得到错误: 严重性代码描述项目文件行抑制状态 错误 CS0233 'a' 没有预定义的大小,因此 sizeof 只能在不安全的上下文中使用(考虑使用 System.Runtime.InteropServices.Marshal.SizeOf)

为什么固定大小的变量需要 Marshal?

来自MSDN: sizeof (C# Reference)

For all other types, including structs, the sizeof operator can be used only in unsafe code blocks. Although you can use the Marshal.SizeOf method, the value returned by this method is not always the same as the value returned by sizeof. Marshal.SizeOf returns the size after the type has been marshaled, whereas sizeof returns the size as it has been allocated by the common language runtime, including any padding.

Used to obtain the size in bytes for an unmanaged type****

很可能真的没有理由需要获取托管类型的字节大小,这正是您正在做的。

“为什么固定大小的变量需要 Marshal?”

如果您要查找的只是局部变量的大小,则不一定非得这样做。您可以简单地调用 var size = sizeof(int)sizeof(short) 这将分别 return 4 and/or 2.