[英]C# Property with no setter - how can it get set from constructor?
您怎么能從構造函數設置僅獲取自動屬性? 下面的代碼顯示了如何從構造函數中設置屬性,但是使用反射表明,幕后確實沒有設置方法。 如果IL中甚至不存在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;
}
}
編譯器將自動實現的只讀屬性轉換為只讀字段和只讀屬性。 構造函數中對屬性的分配被編譯為對基礎字段的分配。
所以你的代碼在這里:
public class GetOnlyProperty
{
public string Thing { get; }
public GetOnlyProperty(string thing)
{
Thing = thing;
}
}
就像您編寫的那樣被編譯為IL:
public class GetOnlyProperty
{
private readonly string _thing;
public string Thing => _thing;
public GetOnlyProperty(string thing)
{
_thing = thing;
}
}
...除了_thing
確實被賦予了“無法_thing
名字”之外,它不是有效的C#標識符。
只讀屬性(僅獲取)具有一個后備readonly
字段,您可能知道,該字段只能在構造函數中設置。
因此,當您擁有object Property { get; }
object Property { get; }
這轉化為
private readonly object _property;
public object get_Property(){return _property;}
並且編譯器知道如果您在構造函數中設置屬性以直接設置字段
因為應該一次或一次分配只讀屬性,否則它的值將始終是該類型的默認值,並且將完全無用。
這是構造函數(除其他明顯的原因之外)用於將值分配給只讀字段的目的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.