[英]Does accessing a static member invoke the base class constructor?
即使所有常識都說不,我仍然在問這個問題只是為了獲得第二意見並確定。
如果我有這樣的類層次結構:
public class IntermediateObjectContext : System.Data.Objects.ObjectContext
{
public static Action<string> PrintHello { get; set; }
}
public class MyDatabaseContext : IntermediateObjectContext
{
public ObjectSet<Foo> Foos
{
get { // ... }
}
}
然后從第三個與Entity Framework對象無關的對象訪問我的IntermediateObjectContext類的靜態成員,在這種情況下,如果我訂閱了該類的委托,那將以某種方式實例化一個新的ObjectContext嗎?
class SomeClass
{
public void SomeMethod()
{
IntermediateObjectContext.PrintHello += SayHello;
}
public void SayHello(string s)
{
Debug.Print(s);
}
}
所有理由都說不,常識說不會,但是我只是想確定一下。 我試圖追蹤一個內存浪費對象。
如果發生什么情況
如果我有一個類似SomeClass類型的靜態集合,那么內存情況將如何處理:
public class SomeClassCollection
{
private static Collection<SomeClass> _col =
new Collection<SomeClass>();
public void Add(SomeClass c) { _col.Add(c); }
public void Remove(SomeClass c) { _col.Remove(c); }
}
然后一些代碼將SomeClass
實例添加到SomeClassCollection中,如下所示:
public SomeClassCollectionConfig
{
public static RegisterSomeClasses()
{
SomeClassCollection.Add(new SomeClass());
SomeClassCollection.Add(new DerivesClassOfSomeClass());
}
}
(1)不,它不會實例化一個對象。
(2)在以下情況下會發生什么:
它將在第一次訪問SomeClassCollection
任何成員時分配空集合col
。
從代碼開始,這就是全部。 您在顯示的代碼中的任何地方都沒有使用_col
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.