有没有一种简单的方法来确定 C# 中的类型大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/363729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a simple way to determine type size in C#?
提问by
Is there a way to say something like:
有没有办法说这样的话:
sizeof(type)? Or type.Size?
大小(类型)?还是 type.Size?
Right now I am looking at using code like:
现在我正在考虑使用如下代码:
if (type.Equals(typeof(int)))
return sizeof(int);
else if (type.Equals(typeof(long)))
return sizeof(long);
etc, etc, for every single data type.
等等,等等,对于每个单一的数据类型。
There must be an cleaner solution, no?
必须有更清洁的解决方案,不是吗?
回答by JaredPar
回答by Daniel Schaffer
If this is for data access, you can do type.GetTypeCode() (which is a member of IConvertible), which gives you a nice enum to switch on.
如果这是用于数据访问,您可以执行 type.GetTypeCode() (它是 IConvertible 的成员),它为您提供了一个很好的枚举来打开。
回答by Lasse V. Karlsen
Look at these questions:
看看这些问题:
- Getting the size of a field in bytes with C#
- How can I get the size of an object in the HttpRuntime.Cache?
- Find out the size of a .net object
In particular, read the answers left by Jon Skeet.
特别是阅读Jon Skeet留下的答案。
回答by Stupid Girl
Maybe you can go
Convert.ToString(type.MaxValue, 2).Length / 8
?
也许你可以去
Convert.ToString(type.MaxValue, 2).Length / 8
?