你怎麼能從構造函數中設置一個只能得到的自動屬性?下面的代碼顯示瞭如何從構造函數中設置屬性,但使用反射顯示幕後真的沒有setter。如果setter方法甚至不存在於IL中,它如何從構造函數調用中設置?C#沒有setter的屬性 - 它如何從構造函數中設置?
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