我在Java中發現了一些相關的問題,但沒有發現任何C#,所以請原諒任何重複。初始化默認構造函數或內聯變量之間有區別嗎?
短而甜,最新的區別?有沒有?
public static class Foo
{
public static List<Bar> Bars;
static Foo()
{
Bars = new List<Bar>();
}
}
public static class Foo
{
public static List<Bar> Bars = new List<Bar>();
}
請參閱@Nick G對非靜態類的回答。我仍然想知道它是否對靜態類有不同的影響。
現在他們不一定是靜態的。這個案子呢?
public class Foo
{
public List<Bar> Bars;
public Foo()
{
Bars = new List<Bar>();
}
}
public class Foo
{
public List<Bar> Bars = new List<Bar>();
}
根據[this](http://jonskeet.uk/csharp/constructors.html),區別在於實例初始化器先運行,然後構造函數運行。文檔[靜態字段初始化](https://msdn.microsoft.com/en-us/library/aa645758(v = vs.71).aspx)和[實例字段初始化](https://msdn.microsoft .com/en-us/library/aa645759(v = vs.71).aspx)都表示字段在構造函數之前被初始化。另請閱讀[這裏](https://blogs.msdn.microsoft.com/ericlippert/2008/02/15/why-do-initializers-run-in-the-opposite-order-as-constructors-part-one/ )爲繼承信息。 – Quantic
我不認爲這完全回答你的靜態問題,但可能有所幫助:http://csharpindepth.com/Articles/General/Beforefieldinit.aspx –
檢查此[文章](http://csharpindepth.com/Articles/General /Beforefieldinit.aspx)對靜態構造函數的存在有一點意義。 – Rafal