c# - 尽管重写了 Struct 默认构造函数

标签 c# struct

我有以下代码:

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/

相关文章:

c - ‘)’ token 和变量未声明错误之前的预期表达式

c++ - 使用 memcpy 复制对象时出现双重释放或损坏错误

c# - (ID/ParentID) 列表到分层列表

c# - UserManager.CreateAsync 不生成 Id

c - 如何从指针到指针引用变量的值?

json - Go JSON解码错误行为如何工作?

c - 在下面的结构成员中存储本地 ipc 缓冲区的地址并传递到 ipcwrite 导致数据损坏

javascript - getJSON 在单击按钮时不起作用,但在按 Enter 键时起作用

c# - 拆分字符串并将它们分配给字典

c# - 扫描的位图横向读取,翻转? (C#)