c# - 你能确定泛型的大小吗?

标签 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
}

如示例中所述,以上是不可能的,但是有没有办法让它起作用?尝试执行 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.
}

最佳答案

你可以使用

Marshal.SizeOf(typeof(T));

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

也许,您可以将通用方法限制为对您有意义的类型,即intlong ,等

还要小心这样的事情 Marshal.SizeoOf(typeof(char)) == 1。

更新

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

What’s the difference? sizeof and Marshal.SizeOf

更新

此外,正如 MickD 所指出的,为了让任何阅读此 Marshal.SizeOf 的年轻 Jedi 都清楚,返回非托管大小。

Marshal.SizeOf Method (Type)

Returns the size of an unmanaged type in bytes.

The size returned is the size of the unmanaged type. The unmanaged and managed sizes of an object can differ. For character types, the size is affected by the CharSet value applied to that class.

关于c# - 你能确定泛型的大小吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49185899/

相关文章:

c# - 迭代和修改集合的最佳实践?

c# - 编写脚本程序

使用 Azure AD 的 C# MVC Web 应用程序在失败之前随机开始重定向大约 10 次

c# - 从 global.asax.cs 调用 JavaScript 函数

c# - 如何编写 LINQ to SQL 查询以获取今天的日期记录?

c# - 如何从 C# 中的 .h 文件中读取常量

C# 确定 SQLite 数据库文件是否经过密码加密

c# - C#中的声音数组

c# - 具有 C# 结构的生产者/消费者?

c# - 如何防止 Entity Framework 强制验证子对象属性?