C# 获取一个对象所占内存的大小

 

        /// <summary>
        /// 获取一个对象所占内存的大小
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="t">实例</param>
        /// <returns>长度(字节数)</returns>
        public static long GetObjectByte<T>(T t) where T : class
        {
            DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream stream = new MemoryStream())
            {
                formatter.WriteObject(stream, t);
                return stream.Length;
            }
        }

  

如果想获取对象的json串,可将上述方法修改一下,就可以将对象序列化为json字符串了。

string result = System.Text.Encoding.UTF8.GetString(stream.ToArray());
return result;

 

如:

        /// <summary>
        /// 获取一个对象json字符串
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="t">实例</param>
        /// <returns>json字符串</returns>
        public static string GetObjectByte<T>(T t) where T : class
        {
            DataContractJsonSerializer formatter = new DataContractJsonSerializer(typeof(T));
            using (MemoryStream stream = new MemoryStream())
            {
                formatter.WriteObject(stream, t);
                string result = System.Text.Encoding.UTF8.GetString(stream.ToArray());
                return result;
            }
      }
posted @ 2021-05-20 16:24  奥兰王子  阅读(1594)  评论(0编辑  收藏  举报