C#
C# 객체의 주소 출력하기
Jundol
2018. 1. 24. 15:39
문득 싱글톤을 공부하다가 객체의 주소값을 출력해보고싶어졌다.
포인터를 사용하면 간단하게 출력될줄 알았으나 복잡한 방법을 거쳐야 출력이된다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConsoleApplication1 | |
{ | |
class Program | |
{ | |
static void Main() | |
{ | |
Singleton s1 = Singleton.Instance(); | |
Singleton s2 = Singleton.Instance(); | |
if (s1 == s2) | |
{ | |
Console.WriteLine("Objects are ths same instance"); | |
unsafe | |
{ | |
TypedReference tr1 = __makeref(s1); | |
TypedReference tr2 = __makeref(s2); | |
IntPtr ptr1 = **(IntPtr**)(&tr1); | |
IntPtr ptr2 = **(IntPtr**)(&tr2); | |
Console.WriteLine(ptr1); | |
Console.WriteLine(ptr2); | |
} | |
} | |
Console.ReadKey(); | |
} | |
} | |
class Singleton | |
{ | |
private static Singleton _instance; | |
protected Singleton() | |
{ | |
} | |
public static Singleton Instance() | |
{ | |
if (_instance == null) | |
{ | |
_instance = new Singleton(); | |
} | |
return _instance; | |
} | |
} | |
} |
위 코드를 보면 unsafe 문 안에 주소를 출력하는 부분이 있다.
변수를 출력하는 방법은 많은데 객체 자체의 주소를 출력하는 글이 없어서 기록해본다.