객체지향 프로그래밍을 하다보면 개체를 참조하는 것으로 개체와 개체간 다양한 관계를 맺어 문제를 풀게 되는데요,
참조하고 있는 개체가 새로운 인스턴스가 되었을 경우 참조하고 있는 쪽에서는 알아서 감지를 할 수는 없습니다. 이런 모양새가 되죠.
이것을 개선할 방법을 코드로 살펴보았습니다.
Console.WriteLine("orignal = new IntValue(15)");
var orignal = new IntValue(15);
var refInstance = orignal;
var refInstance2 = (Ref<IntValue>)(() => orignal);
ref var refInstance3 = ref orignal;
Console.WriteLine($"orign\t: {orignal}");
Console.WriteLine($"=\t: {refInstance}");
Console.WriteLine($"Ref<T>\t: {refInstance2.Get()}");
Console.WriteLine($"ref\t: {refInstance3}");
Console.WriteLine();
orignal = new IntValue(2);
Console.WriteLine("orignal = new IntValue(2)");
Console.WriteLine($"orign\t: {orignal}");
Console.WriteLine($"=\t: {refInstance}");
Console.WriteLine($"Ref<T>\t: {refInstance2.Get()}");
Console.WriteLine($"ref\t: {refInstance3}");
record IntValue(int Value);
readonly record struct Ref<T>(Func<T> Get)
{
//public static explicit operator Ref<T>(Func<T> Get) => new Ref<T>(Get);
public static implicit operator Ref<T>(Func<T> Get) => new(Get);
}
| 출력
orignal = new IntValue(15)
orign : IntValue { Value = 15 }
= : IntValue { Value = 15 }
Ref<T> : IntValue { Value = 15 }
ref : IntValue { Value = 15 }
orignal = new IntValue(2)
orign : IntValue { Value = 2 }
= : IntValue { Value = 15 }
Ref<T> : IntValue { Value = 2 }
ref : IntValue { Value = 2 }
이런 경우 여러분은 어떻게 해결하시나요?
