來源 https://www.cnblogs.com/xiaoyaodijun/p/6605070.htmlhtml
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace ConsoleAppTestDemo1 { class TestDemo1 { [StructLayout(LayoutKind.Sequential)] public class Person { public int Id { get; set; } public string Name { get; set; } public string Sex { get; set; } } // 獲取引用類型的內存地址方法 public string getMemory(object obj) { GCHandle handle = GCHandle.Alloc(obj, GCHandleType.WeakTrackResurrection); IntPtr addr = GCHandle.ToIntPtr(handle); return $"0x{addr.ToString("X")}"; } public void Test() { try { int num = 100000000; var addr1 = getMemory(num); Console.WriteLine($"num: hash code = {num.GetHashCode()} memory addr = {num}"); Person person = new Person() { Id = 99, Name = "Mr.Tom", Sex = "Man" }; var addr2 = getMemory(person); Console.WriteLine($"person: hash code = {person.GetHashCode()} memory addr = {addr2}"); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } } static void Main(string[] args) { TestDemo1 t1 = new TestDemo1(); t1.Test(); } } }
輸出信息:swift
num: hash code = 100000000 memory addr = 100000000 person: hash code = 46104728 memory addr = 0x26810F4 請按任意鍵繼續. . .
參考 函數調用的基本原理:http://www.cnblogs.com/swiftma/p/5468104.html函數
============== Endspa