如何在构造函数完成后立即调用方法?

发布于 2024-10-08 06:16:58 字数 61 浏览 2 评论 0原文

如何在每次执行构造函数时调用一个方法? 换句话说, 在类中,我可以在构造函数完成后立即调用另一个方法吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

十二 2024-10-15 06:16:59

不可以。除非您构造函数中调用它。

或者,您可以使用其他方法,例如 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.

魔法唧唧 2024-10-15 06:16:59

如果我正确理解你的问题,那么这就是你所需要的?

public class SomeMethod
{
    public SomeMethod()
    {
       anotherMethod();
    }

    public void anotherMethod()
    {
    }
}

If I understand your question correctly, then this would be what you need?

public class SomeMethod
{
    public SomeMethod()
    {
       anotherMethod();
    }

    public void anotherMethod()
    {
    }
}
昨迟人 2024-10-15 06:16:59

从语法上讲,可继承类无法将构造函数的调用限制为从另一个例程中调用的代码。可能的是,构造函数会立即抛出异常,除非给它一个有效的特殊令牌,该令牌只能通过使用委托调用的特殊例程获得,该例程创建令牌,将其传递给委托,然后使之无效它在委托返回或抛出之后。然后,该例程还可以在传入的委托返回或抛出之后负责执行任何需要执行的操作。

这是一个令人讨厌的笨拙黑客,但不幸的是,这是我所知道的基类构造函数确保在派生类构造函数抛出异常时清理它拥有的任何非托管资源的唯一方法。

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.

灯角 2024-10-15 06:16:58

您可以将该方法作为构造函数的最后一行调用。

或者,如果您没有该课程,您可以选择面向方面编程(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 )

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文