gpt4 book ai didi

c# - 构造函数允许覆盖 C# 类的一些变量

转载 作者:太空宇宙 更新时间:2023-11-03 20:57:58 26 4
gpt4 key购买 nike

我有这门课:

class Item
{
string reference;
string name;
double price;
double tva;
}

我有一个问题:我正在尝试解决:编写一个允许在实例化期间覆盖引用和名称的构造函数。

这是正确答案吗?

public Item(double priceHT, double RateTVA)
{
Console.Write("Enter reference: ");
reference = Console.ReadLine();
Console.Write("Enter Name: ");
name = Console.ReadLine();

this.priceHT = priceHT;
this.RateTVA = RateTVA;
}

最佳答案

尝试以下操作:

public class Item {

private string reference = string.Empty;
private string name = string.Empty;
private double price = 0.0;
private double tva = 0.0;

//initialize all properties
public Item(string reference, string name, double price, double tva)
{
this.reference = reference;
this.name = name;
this.price = price;
this.tva = tva
}

//use this one to only set reference and name
public Item(string reference, string name)
{
this.reference = reference;
this.name = name;
}

}

使用此模式,您的所有成员都将被正确初始化,并且您将覆盖 referencename。虽然不知道整个目的。

关于c# - 构造函数允许覆盖 C# 类的一些变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48488802/

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