のは、我々が持っているとしましょう:認識されないC#構文
class Foo
{
public int IntPropertyInFoo { get; set; }
public Bar BarPropertyInA { get; set; }
}
class Bar
{
public string StringPropertyInBar { get; set; }
}
その後、我々は、オブジェクト初期化子でFoo
をインスタンス化したいと思います:
public static void Main(string[] args)
{
var foo = new Foo
{
IntPropertyInFoo = 123,
BarPropertyInA = // Ommiting new and type name - why does it compile?
{
StringPropertyInBar = "something"
}
};
}
BarPropertyInA
を初期化する構文は、私をバッフル、コードのコンパイルので、警告なしで、実行すると、NullReferenceException
をスローします。私はその構文を認識しませんが、プロパティではなくフィールドで使用した場合と同じ効果があるようです。コンパイルされたコードを逆アセンブル
はこれを得られます。
.method public hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 34 (0x22)
.maxstack 3
.locals init ([0] class Test.Foo foo)
IL_0000: nop
IL_0001: newobj instance void Test.Foo::.ctor()
IL_0006: dup
IL_0007: ldc.i4.s 123
IL_0009: callvirt instance void Test.Foo::set_IntPropertyInFoo(int32)
IL_000e: nop
IL_000f: dup
IL_0010: callvirt instance class Test.Bar Test.Foo::get_BarPropertyInA()
IL_0015: ldstr "something"
IL_001a: callvirt instance void Test.Bar::set_StringPropertyInBar(string)
IL_001f: nop
IL_0020: stloc.0
IL_0021: ret
} // end of method Program::Main
に似ています:これは、プロパティの/フィールドのメンバーを初期化するためのいくつかの構文糖ことになっている
public static void Main(string[] args)
{
var foo = new Foo
{
IntPropertyInFoo = 123
};
foo.BarPropertyInA.StringPropertyInBar = "something";
}
、/そのプロパティを提供フィールドはコンストラクタで初期化されますか?
私は常に新しいクラスとリストを自分のクラスコンストラクタに追加しています。 – Gavin
'BarPropertyInA'を新しい' Bar'に設定する 'Foo'用のコンストラクタがあれば、' StringPropertyInBar'プロパティを設定することができます。彼らは 'BarPropertyInA.StringPropertyInBar =" something "' – juharr
のようなものではなく、これと一緒に行きました。私は配列のコンストラクタなどを使って同じことを信じています。 .Netはインスタントアートのコンテキストに基づいて最高のコンストラクタを暗示する – maximdumont