我可以使用自己的扩展方法使对象为空吗? [英] Can I null an object with its own extension method?

查看:48
本文介绍了我可以使用自己的扩展方法使对象为空吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Timer类中编写了扩展方法,以在一定时间后销毁它.似乎实际上它只是在timer.enable字段中设置为false,但实际上并没有将整个事情设置为false.有没有一种方法可以从其自身的扩展方法中使对象无效?

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()):

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();
    }

推荐答案

只有在"this"参数也是ref参数(不是)的情况下,这才有可能.

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

所以答案是否定的(在当前的C#实现中)

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

关于另一个问题:实现它的方式没有什么问题(停止计时器并清除对捕获的"killingTimer"变量的引用).

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

这篇关于我可以使用自己的扩展方法使对象为空吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆