gpt4 book ai didi

c# - 结构构造函数调用 this()

转载 作者:太空狗 更新时间:2023-10-29 21:22:07 25 4
gpt4 key购买 nike

我遇到了以下代码片段,想知道以这种方式编写构造函数的目的是什么?

public struct DataPoint{
public readonly long X;
public readonly double Y;
public DataPoint(long x, double y) : this() {
this.X = x;
this.Y = y;
}
}

this() 不只是将XY 设置为零吗?这不是毫无意义的操作,因为之后它们立即设置为 xy 吗?

最佳答案

public DataPoint(long x, double y) : this() {

这会调用编译器自动提供的 struct默认构造函数,并将所有字段初始化为其默认值。

在这种情况下,您的自定义构造函数无论如何都会分配所有字段,因此没有意义。但是假设您只分配了 X,并且没有调用默认构造函数:

public struct DataPoint{
public readonly long X;
public readonly double Y;
public DataPoint(long x) {
this.X = x;
}
}

这会产生编译器错误,因为 Y 没有在您的参数化构造函数中赋值,并且因为您已经定义了它,所以默认构造函数对消费者不公开可见。

this() 添加到初始化列表 确保所有字段都被初始化,即使您不是这样做的人也是如此。

关于c# - 结构构造函数调用 this(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29069565/

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