어떻게 생성자에서 get-only 자동 속성을 설정할 수 있습니까? 아래의 코드는 생성자에서 속성을 설정하는 방법을 보여줍니다. 그러나 리플렉션을 사용하면 실제로 장면 뒤에 setter가 없다는 것을 보여줍니다. setter 메서드가 IL에도 존재하지 않으면 생성자 호출에서 어떻게 설정됩니까?C# setter가없는 속성 - 생성자에서 set을 가져 오는 방법은 무엇입니까?
void Main()
{
var obj = new GetOnlyProperty("original value");
Console.WriteLine(obj.Thing); //works, property gets set from ctor
//get the set method with reflection, is it just hidden..?
//nope, null reference exception
typeof(GetOnlyProperty)
.GetProperty("Thing", BindingFlags.Instance | BindingFlags.Public)
.GetSetMethod()
.Invoke(obj, new object[]{"can't set me to this, setter doen't exist!"});
}
public class GetOnlyProperty
{
public string Thing { get; }
public GetOnlyProperty(string thing)
{
Thing = thing;
}
}
비 추상적 자동 속성 필드를 설정하는 것을 알고 항상 뒷받침 필드를 사용하십시오. 클래스 내부의 속성 설정은 뒷받침 필드 설정으로 변환됩니다. 이벤트는 비슷한 방식으로 작동합니다. – IllidanS4