gpt4 book ai didi

c# - OOP - 如何在类构造函数之前调用函数

转载 作者:太空宇宙 更新时间:2023-11-03 17:43:34 26 4
gpt4 key购买 nike

我明天有一个工作面试,我想回答这个问题:

这个类中有一个名为C的类和方法m,这个类也有空构造函数:

Main ()
{
C c = new c();

}

Class C {

public c {

//empty constructor

}

public m {

//does something - doesnt mind

}

}

您需要做的是更改代码,以便在创建实例类 C 时,方法 m 将在类构造函数之前被调用。

您必须在不更改 main 的情况下执行此操作(仅编辑类代码)。

提前致谢!

最佳答案

就像其他答案所说的那样,您可以将方法设为静态。但是你需要明确地调用它。如果你创建一个静态类构造函数,它将在第一次引用该类时自动调用一次(你不需要调用它)(就像你构造第一个实例时一样)。您无法完全控制它何时执行,但它会在第一个实例构造之前执行。根据他们对问题的措辞方式(您不能更改 Main 方法),我认为静态类构造函数是他们正在寻找的答案。

http://msdn.microsoft.com/en-us/library/k9x6w0hc%28v=vs.80%29.aspx

Static constructors have the following properties: A static constructor does not take access modifiers or have parameters. A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. A static constructor cannot be called directly. The user has no control on when the static constructor is executed in the program.

Java 没有静态类构造函数,但它们有静态初始化 block ..

static {
// code in here
}

关于c# - OOP - 如何在类构造函数之前调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11066727/

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