如果我们在类中只有一个参数化的构造函数,那么为什么我们不能使用默认构造函数创建对象呢?与添加参数化构造函数之前一样,类中没有默认构造函数!尽管如此,可以通过默认构造函数创建 lass 的实例。但是在添加参数化构造函数后,默认构造函数停止工作。为什么?
谁能解释一下?
class Program
{
static void Main(string[] args)
{
Test test = new Test(); //instance created using parameterized constructor
Test2 test = new Test2(); //instance can not be created using default constructor
}
class Test
{
//no constructor present
}
class Test2
{
public Test2(int a)
{
//parameterized constructor present
}
}
}
最佳答案
如果您不添加任何构造函数,编译器会为您添加一个无参数构造函数作为默认构造函数。
如果添加任何构造函数,则不会添加默认构造函数。如果您仍然需要无参数构造函数,则需要手动添加它。
官方docs说:
A constructor like this one, which takes no arguments, is called a default constructor.
[....]
If a class does not have a constructor, a default constructor is automatically generated and default values are used to initialize the object fields.
当您添加参数化构造函数时,您基本上是在说此类需要这些特定参数才能正确初始化。如果无参数构造函数仍然有效,您将无法强制使用该特定构造函数。您必须定义一个私有(private)默认构造函数以避免使用它。
关于c# - 为什么添加参数化构造函数时默认构造函数不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52026384/