我的秋季學期將包括使用 c#,所以我正在努力爭取盡可能的優勢。我想做的第一件事是了解抽象類,但我在使我的代碼工作時遇到困難。它是一個“item”類,有 3 個 .cs 文件,包括主項目類。這是抽象類。using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApp6{ abstract public class item { public abstract string prodName { set; } public abstract int amount(); }}這是子類。using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApp6{ public class ProteinPowder : item // Says it doesn't implement anything. { private string name; private int itemAmount; public proPowder(string name, int amount) // Is this correct? { this.name = name; this.itemAmount = amount; } public string Name { set => name = value; } public int Amount { set => itemAmount = value; } }}主項目目前是空的。我認為可以通過正確實施 ProteinPowder 來解決這些問題,但我無法讓它發揮作用。有人可以指出我做錯了什么嗎?** 編輯 ***這看起來更好嗎?using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApp6{ public class ProteinPowder : item { private string name; private int itemAmount; public ProteinPowder(string name, int amount) { this.name = name; this.itemAmount = amount; } public int Amount { set => itemAmount = value; } public override string prodName { set => throw new NotImplementedException(); } public override int amount() { throw new NotImplementedException(); } }}
1 回答

寶慕林4294392
TA貢獻2021條經驗 獲得超8個贊
簡而言之,抽象類是說“任何實現我的東西都必須為我擁有的所有抽象屬性/方法提供實現”。
就您而言,item有 2 個抽象項目。prodName和amount。
這意味著在你的ProteinPowder課堂上,你需要實現這些,例如
public override string prodName { set => /*do something specific for ProteinPowder*/}
public override int amount()
{
// do something specific for ProteinPowder
}
你提出的第二件事public proPowder(string name, int amount) // Is this correct?,答案是否定的。
由于缺少返回類型,我假設這應該是構造函數。構造函數必須與類的名稱匹配,因此應為
public ProteinPowder(string name, int amount)
- 1 回答
- 0 關注
- 139 瀏覽
添加回答
舉報
0/150
提交
取消