开发者

How to properly dispose of an object

开发者 https://www.devze.com 2023-01-03 08:59 出处:网络
I am experiencing something weird and have a workaround already, but I don\'t think I understood it well.

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....

I feel like I am forgetting something critical here?

Foo's guts look like:

public delegate void Delegate1(T t);
public Delegate1 Delegate1H开发者_如何学运维andler { 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! (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() would be called every time you run Method()


I think @hans was getting at something like this in his comment

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; }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号