代码之家  ›  专栏  ›  技术社区  ›  VoodooChild

如何正确处置对象

  •  2
  • VoodooChild  · 技术社区  · 14 年前

    我经历了一些奇怪的事情,已经有了一个解决办法,但我觉得我不太明白。

    如果我在一个类中多次调用下面的方法:

    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”,它的delegate1处理程序位于“method”之外,其中 委托1管理人 只有初始化一次,“A”才能重新初始化-没问题!(或者可能是我不知道)

    2 回复  |  直到 14 年前
        1
  •  1
  •   Jay    14 年前

    a.Delegate1Handler = ViewSomething();

    对我来说,这意味着 ViewSomething() 返回委托的方法。

    查看某事() 每次你跑步都会打电话来 Method()

        2
  •  0
  •   µBio    14 年前

    我认为@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; }