c# - 在构造函数中设置字段值
问题描述
我很想知道编写构造函数的正确方法是什么,或者更确切地说,我何时以这种方式或其他方式编写它。我还想知道为什么要更改构造函数中的字段名称,就像我在第一个构造函数中使用字段地址所做的那样。感谢您的帮助。
例如,假设您有一个包含四个字段的 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;
}
}
解决方案
我会像这样更改默认构造函数定义,
public Shipment : this ("Football jersey", 35.99, "8520 Washington Dr.Toledo, OH 43612", 0.400 )
{
}
这重用了参数化构造函数并使您的代码更加简洁。
您的其余代码都可以。在构造函数中使用 this 是非常标准的,它可以防止您为构造函数参数(例如 addressParams)发明其他名称。
推荐阅读
- javascript - 根据另一个字段的值在表单控制字段上设置错误
- java - 当我打印引用变量时,它会打印对象的地址。但是当我打印 String 类的引用变量时,它会打印一个字符串
- c - 执行有界加法的最有效方法是什么?
- ffmpeg - ffmpeg 从 h264 转换为网络服务器
- rust - 为什么我的 rust 函数会出现“返回引用当前函数拥有的数据的值”错误?
- jdbc - 与 Domino v12 的 JDBC 连接
- javascript - 如何比较具有相同对象属性的两个值?
- postgresql - 将表名作为参数传递给 Postgresql
- google-chrome-devtools - 如何从另一台机器访问 chromebook 上的 chrome 开发工具
- javascript - 状态改变回调函数