猿问

试图学习课程陷入了死胡同

我的秋季学期将包括使用 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();

        }

    }

}


qq_遁去的一_1
浏览 120回答 1
1回答

宝慕林4294392

简而言之,抽象类是说“任何实现我的东西都必须为我拥有的所有抽象属性/方法提供实现”。就您而言,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)
随时随地看视频慕课网APP
我要回答