你能确定一般类型的大小吗?

Asd*_*dar 5 c#

有没有办法获得sizeof()通用类型?例如

public int GetSize<T>()
{
    return sizeof(T); //this wont work because T isn't assigned but is there a way to do this
}
Run Code Online (Sandbox Code Playgroud)

正如在例子中所说,以上是不可能的,但有没有办法让它工作?尝试过,public unsafe int但它没有改变任何东西.真的不想做点什么

public int GetSize<T>()
{
    if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte))
    {
        return 1;
    }
    else if (typeof(T) == typeof(short) || typeof(T) == typeof(ushort) || typeof(T) == typeof(char))
    {
        return 2;
    }
    //and so on.
}
Run Code Online (Sandbox Code Playgroud)

AAA*_*ddd 6

您可以使用

\n
Marshal.SizeOf(typeof(T));\n
Run Code Online (Sandbox Code Playgroud)\n

请务必注意,如果滥用它,将会引发各种意想不到的结果。

\n

也许,您可以对通用方法进行限制,使其Types对您有意义,即intlong等等。

\n

类似这样的事情也要警惕Marshal.SizeoOf(typeof(char)) == 1.

\n

更新

\n

正如MickD在他的评论中所发表的,(毫不奇怪)编译器向导Eric Lippert发表了一篇关于一些细节的博客文章

\n

xe2x80x99 有什么区别?sizeof 和 Marshal.SizeOf

\n

更新

\n

另外,正如MickD所指出的那样,为了让任何年轻的绝地武士读到这一点,这Marshal.SizeOf会返回不受管理的大小。

\n

Marshal.SizeOf 方法(类型)

\n
\n

返回非托管类型的大小(以字节为单位)。

\n

返回的大小是非托管类型的大小。对象的非托管和\n托管大小可能不同。对于字符类型,大小受应用于该类的 CharSet 值影响。

\n
\n