嘿伙计们我不确定当我从主要代码启动我的控制台时,它会打印两次不确定的项目,因为我根本没有循环方法:
FoodProducts FoodProd1 = new FoodProducts("FP001", "Meat", 15.99, 200, 100, "Australia");
FoodProducts FoodProd2 = new FoodProducts("FP002", "Bread", 2.99, 150, 50, "Italy");
FoodProd1.Print();
FoodProd2.Print();
class FoodProducts : Products
{
private string origin;
public FoodProducts(string id, string name, double price, int soldCount, int stockCount, string origin)
: base(id, name, price, soldCount, stockCount)
{
this.origin = origin;
//Need to find out why this code prints both lines and not in single line and why it starts from Product 2 when it is printed on the console
PrintOrigin();
}
private string Origin
{
get { return origin; }
set { origin = value; }
}
public void PrintOrigin()
{
base.Print();
Console.WriteLine("Origin: {0}", this.Origin);
}
更新自评论
基类中定义的Print()
方法:
public void Print() {
Console.WriteLine("Product ID: {0}", this.id);
Console.WriteLine("Product Name: {0}", this.name);
Console.WriteLine("Prodcut Price: {0}", this.price);
Console.WriteLine("Sold Counter: {0}", this.soldCount);
Console.WriteLine("Stock Count: {0}", this.stockCount);
Console.WriteLine();
Console.ReadKey();
}
答案 0 :(得分:6)
目前还不清楚您希望输出的样子。我根据您之前的问题拼凑了一个产品类。它的输出看起来像这样。
如您所见,它会像您提到的那样打印两次信息。不清楚的是,您是否希望每次拨打电话时打印原点,如果是,请调用PrintOrigin
方法而不是打印方法。否则,如果您只想在构造时打印原点,请从Print
方法中调出PrintOrigin
方法。
调用PrintOrigin而不是Print的第一个示例,并从构造函数中删除PrintOrigin语句。
如果要将Method调用保持为Print而不是PrintOrigin,则声明Base Method Virtual并覆盖它。 即。
class Program
{
static void Main(string[] args)
{
FoodProducts FoodProd1 = new FoodProducts("FP001", "Meat", 15.99, 200, 100, "Australia");
FoodProducts FoodProd2 = new FoodProducts("FP002", "Bread", 2.99, 150, 50, "Italy");
FoodProd1.Print();
FoodProd2.Print();
Console.ReadLine();
}
}
public class Products
{
string id;
string name;
double price;
int soldCount;
int stockCount;
public Products(string id, string name, double price,
int soldCount, int stockCount)
{
this.id = id;
this.name = name;
this.price = price;
this.soldCount = soldCount;
this.stockCount = stockCount;
}
public virtual void Print()
{
Console.WriteLine("Product ID: {0}", this.id);
Console.WriteLine("Product Name: {0}", this.name);
Console.WriteLine("Prodcut Price: {0}", this.price);
Console.WriteLine("Sold Counter: {0}", this.soldCount);
Console.WriteLine("Stock Count: {0}", this.stockCount);
Console.WriteLine();
}
}
class FoodProducts : Products
{
private string origin;
public FoodProducts(string id, string name, double price, int soldCount, int stockCount, string origin)
: base(id, name, price, soldCount, stockCount)
{
this.origin = origin;
}
private string Origin
{
get { return origin; }
set { origin = value; }
}
public override void Print()
{
base.Print();
Console.WriteLine("Origin: {0}", this.Origin);
}
}