我有以下代码:
struct Person
{
public readonly int x;
public Person( int x )
{
this.x = x;
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person();
Console.Write(p.x);
}
}
这段代码运行良好。为什么?覆盖默认构造函数是否未应用于结构? 使用参数化构造函数是否覆盖了默认构造函数?
最佳答案
您没有覆盖默认构造函数;您刚刚提供了一个接受一个参数的重载。与类不同,结构的参数化构造函数并不意味着不会自动生成默认构造函数。 C# 编译器自动为结构提供了一个默认的、无参数的构造函数,它不允许你用你自己的来覆盖它。这就是结构的本质。
来自 Using Structs (C# Programming Guide)
It is an error to define a default (parameterless) constructor for a struct. It is also an error to initialize an instance field in a struct body. You can initialize struct members only by using a parameterized constructor or by accessing the members individually after the struct is declared. Any private or otherwise inaccessible members can be initialized only in a constructor.
如果您真的想要求您的数据类型的用户调用自定义构造函数,则必须改用类。
关于c# - 尽管重写了 Struct 默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19751210/