【发布时间】:2017-09-23 15:56:44
【问题描述】:
为什么你可以从构造函数中设置一个只获取的自动属性?下面的代码显示了如何从构造函数设置属性,但使用反射表明幕后确实没有设置器。如果在 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;
}
}
【问题讨论】:
-
非抽象自动属性始终使用支持字段。在类中设置属性被转换为设置支持字段。事件以类似的方式工作。