[英]How to properly dispose of an object
I am experiencing something weird and have a workaround already, but I don't think I understood it well. 我遇到了一些奇怪的问题,并且已经有了解决方法,但是我认为我不太了解。
If I call the Method below numerous times within a class: 如果我在一个类中多次调用下面的方法:
public void Method()
{
Foo a = new Foo();
a.Delegate1Handler = ViewSomething();
}
If I call Method() multiple times in one instance of the class that it is in... I am reinitializing "a" every time but for some reason a.Delegate1Handler
is still around from the previous initialization, and therefore ViewSomething() is called again and again and again.... 如果我多次在类的一个实例中调用Method(),则每次都会重新初始化“ a”,但由于某种原因
a.Delegate1Handler
仍在上一次初始化中,因此ViewSomething()为一次又一次地打电话来。
I feel like I am forgetting something critical here? 我觉得我在这里忘记了一些重要的事情吗?
Foo's guts look like: Foo的胆量看起来像:
public delegate void Delegate1(T t);
public Delegate1 Delegate1Handler { get; set; }
EDIT: (workaround that I put in is described below, but I still don't understand exactly why it was behaving like this) -> 编辑:(下面介绍了我所采用的解决方法,但我仍然不明白为什么它会像这样运行)->
Initialized "a" and it's delegate1Handler outside of "Method" where delegate1Handler only gets initialized once and "a" can again get reinitialized - no problem! 初始化了“ a”,并且它是“ Method”之外的“ delegate1Handler ”,在此“ delegate1Handler”仅被初始化一次,“ a”可以再次被初始化-没问题! (or maybe it is I don't know)
(或者也许是我不知道)
a.Delegate1Handler = ViewSomething();
To me, this suggests that ViewSomething()
is a method that returns a delegate. 对我来说,这表明
ViewSomething()
是一种返回委托的方法。
ViewSomething()
would be called every time you run Method()
每次运行
Method()
时都会调用ViewSomething()
Method()
I think @hans was getting at something like this in his comment 我认为@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.