[英]How to properly dispose of an object
我遇到了一些奇怪的問題,並且已經有了解決方法,但是我認為我不太了解。
如果我在一個類中多次調用下面的方法:
public void Method()
{
Foo a = new Foo();
a.Delegate1Handler = ViewSomething();
}
如果我多次在類的一個實例中調用Method(),則每次都會重新初始化“ a”,但由於某種原因a.Delegate1Handler
仍在上一次初始化中,因此ViewSomething()為一次又一次地打電話來。
我覺得我在這里忘記了一些重要的事情嗎?
Foo的膽量看起來像:
public delegate void Delegate1(T t);
public Delegate1 Delegate1Handler { get; set; }
編輯:(下面介紹了我所采用的解決方法,但我仍然不明白為什么它會像這樣運行)->
初始化了“ a”,並且它是“ Method”之外的“ delegate1Handler ”,在此“ delegate1Handler”僅被初始化一次,“ a”可以再次被初始化-沒問題! (或者也許是我不知道)
a.Delegate1Handler = ViewSomething();
對我來說,這表明ViewSomething()
是一種返回委托的方法。
每次運行Method()
時都會調用ViewSomething()
Method()
我認為@hans在他的評論中遇到了類似問題
public void Method()
{
Foo a = new Foo( ViewSomething );
}
// ...
public class Foo
{
public Foo( Delegate1 del ) // note: accepting the delegate parameter
{
DelegateHandler = del;
}
}
public delegate void Delegate1(T t);
public Delegate1 Delegate1Handler { get; set; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.