结构构造函数调用this() [英] Struct constructor calls this()

查看:95
本文介绍了结构构造函数调用this()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  public struct DataPoint {
public readonly long X;
公共只读双精度Y;
public DataPoint(long x,double y):this(){
this.X = x;
this.Y = y;
}
}

不要 this( )只是将 X Y 设置为零?

$ b是不是毫无意义的动作,因为事后它们立即被设置为 x y ? $ b

解决方案

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

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



在这种情况下,您的自定义构造函数总是分配所有字段,因此没有意义。但是,假设您只分配了 X ,而没有调用默认构造函数:

  public struct DataPoint {
public readonly long X;
公共只读双精度Y;
public DataPoint(long x){
this.X = x;
}
}

这会产生编译器错误,因为 Y 未在参数化构造函数中分配,并且由于已定义,因此默认构造函数对消费者不公开可见。



this()添加到初始化列表可以确保所有字段都已初始化,即使您不是一个初始化的人。 / p>

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?

解决方案

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.

这篇关于结构构造函数调用this()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆