gpt4 book ai didi

C#创建类实例时执行类内的方法

转载 作者:行者123 更新时间:2023-11-30 14:22:46 25 4
gpt4 key购买 nike

public class TestClass
{
private void Method1() {...}
}

是否可以在我初始化类后立即执行 method1?如果是这样,我该怎么做?

我不知道如何表达我的问题,如果已经有类似的问题,我深表歉意

最佳答案

是的,来自 constructor :

public class TestClass
{
public TestClass()
{
// initialize here...
// then call your method:
Method1();
}

private void Method1() {...}
}

如果此方法需要很长时间才能执行,则它不适合构造函数,因为调用者可能不会期望这一点。然后你应该让你的方法public(有一个有意义的名字)然后让它被调用。构造函数应该初始化对象而不是使用它们。

关于C#创建类实例时执行类内的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48171889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com