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

后端 未结 7 2042
暗喜
暗喜 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

    Following on from Cory's answer, if performance is important and you need to hit this code a lot then you could cache the size so that the dynamic method only needs to be built and executed once per type:

    int x = 42;
    Console.WriteLine(Utils.SizeOf(x));    // Output: 4
    
    // ...
    
    public static class Utils
    {
        public static int SizeOf(T obj)
        {
            return SizeOfCache.SizeOf;
        }
    
        private static class SizeOfCache
        {
            public static readonly int SizeOf;
    
            static SizeOfCache()
            {
                var dm = new DynamicMethod("func", typeof(int),
                                           Type.EmptyTypes, typeof(Utils));
    
                ILGenerator il = dm.GetILGenerator();
                il.Emit(OpCodes.Sizeof, typeof(T));
                il.Emit(OpCodes.Ret);
    
                var func = (Func)dm.CreateDelegate(typeof(Func));
                SizeOf = func();
            }
        }
    }
    

提交回复
热议问题