どのようにして、コンストラクタから取得専用の自動プロパティを設定できますか?以下のコードは、コンストラクタからプロパティを設定する方法を示していますが、リフレクションを使用すると、本当にシーンの背後にセッターがないことがわかります。 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