C#: Getting size of a value-type variable at runtime?

后端 未结 7 2041
暗喜
暗喜 2020-11-30 08:41

I know languages such as C and C++ allow determining the size of data (structs, arrays, variables...) at runtime using sizeof() function. I tried that in C# and apparently i

7条回答
  •  孤独总比滥情好
    2020-11-30 09:29

    public static class TypeSize
    {
        public static int GetSize(this T value)
        {
            if (typeof(T).IsArray)
            {
                var elementSize = GetTypeSize(typeof(T).GetElementType());
                var length = (value as Array)?.GetLength(0);
                return length.GetValueOrDefault(0) * elementSize;
            }
            return GetTypeSize(typeof(T));
        }
    
        static ConcurrentDictionary _cache = new ConcurrentDictionary();
    
        static int GetTypeSize(Type type)
        {
            return _cache.GetOrAdd(type, _ =>
            {
                var dm = new DynamicMethod("SizeOfType", typeof(int), new Type[0]);
                ILGenerator il = dm.GetILGenerator();
                il.Emit(OpCodes.Sizeof, type);
                il.Emit(OpCodes.Ret);
                return (int)dm.Invoke(null, null);
            });
        }
    }
    

提交回复
热议问题