首页 > 解决方案 > 在构造函数中设置字段值

问题描述

我很想知道编写构造函数的正确方法是什么,或者更确切地说,我何时以这种方式或其他方式编写它。我还想知道为什么要更改构造函数中的字段名称,就像我在第一个构造函数中使用字段地址所做的那样。感谢您的帮助。

例如,假设您有一个包含四个字段的 Shipment 类:String item、Double price、String address、Double weight。

 class Shipment
 {
  private string item;
  private double price;
  private string address;
  private double weight;

   public Shipment(string item, double price, string addr, double weight)
   {
      this.item=item;
      this.price=price;
      address=addr;
      this.weight=weight;
   }

   public Shipment()
   {
   item="Football jersey";
   price=35.99;
   address="8520 Washington Dr.Toledo, OH 43612"
   weight=0.400;
  }

 }

标签: c#constructor

解决方案


我会像这样更改默认构造函数定义,

public Shipment : this ("Football jersey", 35.99, "8520 Washington Dr.Toledo, OH 43612", 0.400 )
{
}

这重用了参数化构造函数并使您的代码更加简洁。

您的其余代码都可以。在构造函数中使用 this 是非常标准的,它可以防止您为构造函数参数(例如 addressParams)发明其他名称。


推荐阅读