如何获取通用列表中类型的字节大小? [英] how to get byte size of type in generic list?

查看:118
本文介绍了如何获取通用列表中类型的字节大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个通用列表,我想获取类型的字节大小,例如T是字符串还是int等.我尝试了用getByteSize()编写的两种方式,只是让你知道我正在使用一次一种方式...

I have this generic list and I want to get the byte size of the type like if T is string or int etc., I tried both ways as written in getByteSize(), and just to let you know I am using only one way at a time ...

但是当我尝试编译时,它给出一个错误,提示错误:找不到类型或名称空间名称'typeParameterType'(您是否缺少using指令或程序集引用?)"

but when I try to compile, it gives an error saying "Error: The type or namespace name 'typeParameterType' could not be found (are you missing a using directive or an assembly reference?)"

public class iList<T> : List<T> 
    { 
        public int getByteSize ()
        {
            // way 1
            Type typeParameterType = typeof(T);
            return sizeof(typeParameterType);

            // way 2
            Type typeParameterType = this.GetType().GetGenericArguments()[0];
            return sizeof(typeParameterType);
        }
    }

知道我在做什么错吗?

推荐答案

sizeof仅适用于值类型.

对于字符串,在填充之前,您将不知道实际字节的大小.

For a string, you won't know the actual byte size until you populate it.

如果您打算这样做,请序列化列表并进行测量.虽然这不是保证的方法,但它可能比其他方法更好.如果没有任何真正的努力,它根本无法满足您的需求.您可以像这样执行快速而肮脏的计数:

If you are set on doing this, serialize the list and measure it then. While not a guaranteed way, it is probably better than the alternative. Scratch that. It won't get you what you want without some real effort, if at all. You could perform a quick and dirty count like so:

public int getListSize()
{
    Type type = typeof(T);

    if (type.IsEnum)
    {
        return this.Sum(item => Marshal.SizeOf(Enum.GetUnderlyingType(type)));
    }
    if (type.IsValueType)
    {
        return this.Sum(item => Marshal.SizeOf(item));
    }
    if (type == typeof(string))
    {
        return this.Sum(item => Encoding.Default.GetByteCount(item.ToString()));
    }
    return 32 * this.Count;
}

如果您真的想了解更多有关大小的信息,请参见

If you really want to know more about size, here is a comprehensive answer on the topic.

这篇关于如何获取通用列表中类型的字节大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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