Can I null an object with its own extension method?

末鹿安然 提交于 2019-12-11 02:31:47

问题


I wrote extension method to Timer class to destroy it after certain amount of time. seems like it actually only set false in timer.enable fields but don't really set the whole things to false. Is there a way to nullify an object from it own extension method?

and another thing - is it good practice to implement it in that way or I should expect sync issues and more surprises?

timer.DestroyAfter(1.Hours()) :

     public static void DestroyAfter(this Timer timer, TimeSpan timeSpan)
      {
        var killingTimer = new Timer(timeSpan.TotalMilliseconds)
            {
                AutoReset = false,
            };

        killingTimer.Elapsed += (sender, e) =>
            {
                timer.Stop();
                **timer = null;** //doesn't seem to work though line is executed
                killingTimer.Stop();
                killingTimer = null;
            };
        killingTimer.Start();
    }

回答1:


This would only be possible if the "this" parameter was also a ref parameter, which it is not.

So the answer is no (in the current C# implementation)

Regarding your other question: there's nothing wrong with the way you implemented it (stopping the timer and clearing the reference to the captured "killingTimer" variable).




回答2:


There is nothing special about extensions methods. What the this modifier says it that call like timer.DestroyAfter(time) should be compiled as if you wrote DestroyAfter(timer, time).

And in normal methods, change to the parameter variable doesn't affect the original variable. In normal methods, there is a way to achieve that: use ref parameter. But you can't do that with the this parameter of an extension method.

Besides, this would be very confusing: If I write timer.DestroyAfter(time), then suddenly some time in the future, timer becomes null? I certainly would not expect that.



来源:https://stackoverflow.com/questions/11922839/can-i-null-an-object-with-its-own-extension-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!