Struct constructor calls this()

我的未来我决定 提交于 2019-12-21 12:37:26

问题


I came across the following code snippet and was wondering what the purpose of writing a constructor this way was?

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

Doesn't this() just set X and Y to zero? Is this not a pointless action seeing as afterwards they are immediately set to x and y?


回答1:


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

This calls the default constructor for the struct, which is automatically provided by the compiler, and will initialize all fields to their default values.

In this case, your custom constructor is assigning all fields anyway, so there's no point. But let's say you only assigned X, and didn't call the default constructor:

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

This would generate a compiler error, because Y is not assigned in your parameterized constructor, and because you've defined it, the default constructor is not publicly visible to consumers.

Adding this() to the initialization list ensures that all fields are initialized, even if you aren't the one to do so.



来源:https://stackoverflow.com/questions/29069565/struct-constructor-calls-this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!