gpt4 book ai didi

无法解决方法重载

转载 作者:太空宇宙 更新时间:2023-11-04 05:48:52 24 4
gpt4 key购买 nike

我试图用 FreshItem 子类中的新方法重载 PurchasedItem 中的 FindCost 方法。新的 FreshItem FindCost 方法使用重量而不是数量来确定成本。

我收到错误:

There is no argument given that corresponds to the required formal parameter 'gItem'

'Program.GroceryItem.PurchasedItem.FreshItem.FindCost()' hides inherited member 'Program.GroceryItem.PurchasedItem.FindCost()'. Use the new keyword if hiding was intended.

如果项目是新鲜的,我如何允许使用 FreshItem FindCost 方法?

    class Program
{
public class GroceryItem
{
public string Name;
public double Price;

public PurchasedItem pItem
{
get;
set;
}

public GroceryItem()
{
}

public GroceryItem(string name, double price)
{
this.Name = name;
this.Price = price;
}
public class PurchasedItem
{
public int Quantity;
GroceryItem item;
public PurchasedItem(GroceryItem gItem)
{
item = new GroceryItem(gItem.Name, gItem.Price);
}

public double FindCost()
{
return item.Price * this.Quantity * 1.10;
}

public class FreshItem : PurchasedItem
{
public FreshItem()
{
}
public double weight;

public double FindCost()
{
return this.item.Price * this.weight;
}

}
}
public static void Main(string[] args)
{
var item1 = new GroceryItem("Lettuce", 2.05);
item1.pItem = new GroceryItem.PurchasedItem(item1);
item1.pItem.Quantity = 12;
double cost1 = item1.pItem.FindCost();


Console.WriteLine(item1.Name + " " + item1.Price);
Console.WriteLine(cost1);
}
}
}

最佳答案

当基类有带参数的构造函数时,你应该明确地调用它。它必须是:

public FreshItem():base(/*pass paramter*/)
{
}

参见:Derived class explicit base constructor call

对于第二个问题,PurchasedItemFreshItem 必须继承自 GroceryItem 并实现 FindMethod:

public abstract class GroceryItem
{
public string Name {set;get;}
public double Price {set;get;}

public GroceryItem(string name, double price){
this.Name = name;
this.Price = price;
}

public abstract double FindCost();
}
public class PurchasedItem: GroceryItem
{
public int Quantity {set;get;}
public PurchasedItem(string name, double price, int quntity):base(name, price)
{
this.Quantity = quntity;
}

public override double FindCost()
{
return this.Price * this.Quantity * 1.10;
}


}
public class FreshItem : GroceryItem
{
public double Weight {set;get;}

public FreshItem(string name, double price, int weight) : base(name, price)
{
this.Weight= weight;
}
public override double FindCost()
{
return this.Price * this.Weight;
}
}


public static void Main(string[] args)
{
var item1 = new PurchasedItem("Lettuce", 2.05,12);
double cost1 = item1.FindCost();
}

关于无法解决方法重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50013577/

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