如何在构造函数完成后立即调用方法?
如何在每次执行构造函数时调用一个方法? 换句话说, 在类中,我可以在构造函数完成后立即调用另一个方法吗?
How can I call a method every time when constructor is executed?
In other words,
Within a class, can I somehow call another method as soon as constructor is completed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不可以。除非您在构造函数中调用它。
或者,您可以使用其他方法,例如
Init()
,但客户端需要记住来调用它。No. Unless you call it within your constructor.
Alternatively you can have another method such as
Init()
, but the client needs to remember to call it.如果我正确理解你的问题,那么这就是你所需要的?
If I understand your question correctly, then this would be what you need?
从语法上讲,可继承类无法将构造函数的调用限制为从另一个例程中调用的代码。可能的是,构造函数会立即抛出异常,除非给它一个有效的特殊令牌,该令牌只能通过使用委托调用的特殊例程获得,该例程创建令牌,将其传递给委托,然后使之无效它在委托返回或抛出之后。然后,该例程还可以在传入的委托返回或抛出之后负责执行任何需要执行的操作。
这是一个令人讨厌的笨拙黑客,但不幸的是,这是我所知道的基类构造函数确保在派生类构造函数抛出异常时清理它拥有的任何非托管资源的唯一方法。
There is no way syntactically for an inheritable class to restrict the calling of a constructor to code that is called from within another routine. What is possible is to have a constructor throw an immediate exception unless it's given a valid special token, which can only be obtained via special routine which is called with a delegate, and which creates the token, passes it to the delegate, and then invalidates it after the delegate returns or throws. That routine could then also take care of doing whatever needs to be done after the passed-in delegate either returns or throws.
Rather a nasty klunky hack, but unfortunately it's the only way I know of for a base class constructor ensure the cleanup of any unmanaged resources it owns if a derived-class constructor throws an exception.
您可以将该方法作为构造函数的最后一行调用。
或者,如果您没有该课程,您可以选择面向方面编程(http://en.wikipedia。 org/wiki/Aspect_oriented_programming )
You can just call the method as the last line of the constructor.
Alternatively if you don't own the class you can go for Aspect Oriented Programming ( http://en.wikipedia.org/wiki/Aspect_oriented_programming )