我有一个通用列表,我想获得类型的字节大小,比如T是字符串或整数等。我尝试了getByteSize()中写的两种方法,并且只使用一种方法...
但是当我尝试编译时,它会出现错误,指出“错误:找不到'typeParameterType'的类型或命名空间名称(是否缺少using指令或程序集引用?)”
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
仅适用于 非托管 类型,这些类型仅是值类型的 _子集_(也包括不安全指针类型);例如,typeof(System.DateTime).IsValueType
是true
,但你不能使用它与sizeof
。Encoding.Default
指的是 磁盘上 的默认字符编码(在 .NET 中为 ANSI,在 .NET Core 中为 UTF-8),而不是 内存中 的编码,后者始终为 UTF-16;因此,应该使用item.ToString().Length * sizeof(char)
。 - mklement0