C# 构造函数允许覆盖C类的一些变量
我有这门课:C# 构造函数允许覆盖C类的一些变量,c#,C#,我有这门课: class Item { string reference; string name; double price; double tva; } 我有一个问题:我正在试图解决:编写一个构造函数,允许在实例化过程中覆盖引用和名称 这是正确的答案吗 public Item(double priceHT, double RateTVA) { Console.Write("Enter reference: "); reference = Co
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;
}
}
使用此模式,所有成员都将被正确初始化,您将覆盖引用和名称。不过,我不知道全部目的。尝试以下方法:
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;
}
}
使用此模式,所有成员都将被正确初始化,您将覆盖引用和名称。虽然我不知道它的全部用途。可能是,但你不应该在构造函数中查询用户输入。我可以只写一个引用和名称的构造函数吗?@bash.d我知道这感觉很尴尬,但我不明白为什么会出现问题?理想情况下,如果您希望允许字符串引用和字符串名称参数重写它们,则构造函数将接受它们。@bashrc在我99.99%的情况下,我根本不会这样做。如果需要使用外部输入构造对象,请使用参数。此外,构造函数依赖于控制台来构造对象。我相信我从来没有这样做过,也可能永远不会这样做。可能是,但你不应该在构造函数中查询用户输入。我能写一个只包含引用和名称的构造函数吗?@bash.d我知道这感觉很尴尬,但我不明白为什么会出现问题?理想情况下,如果您希望允许字符串引用和字符串名称参数重写它们,则构造函数将接受它们。@bashrc在我99.99%的情况下,我根本不会这样做。如果需要使用外部输入构造对象,请使用参数。此外,构造函数依赖于控制台来构造对象。我相信我从来没有这样做过,也可能永远不会这样做。