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

时间:2018-01-28 16:49:18

标签: c#

我有这堂课:

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;
}

1 个答案:

答案 0 :(得分:4)

尝试以下方法:

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。但是,不知道整个目的。