簡體   English   中英

從基礎 class C# 繼承字段

[英]Inheriting fields from a base class C#

我無法讓 class 從其父 class 繼承字段。

我想讓 BullFrog class 和 Toad class 繼承 Amphibian class 的所有屬性,然后覆蓋權重屬性。 我認為它默認繼承了父 class 的所有特征,我在這里缺少什么?

public class Animal
    {
        public string sound { get; set; }
        public string move { get; set; }
        public string favSnack { get; set; }
        public double avgWeight { get; set; }
        public void Speak(string sound)
        {
            Console.WriteLine( $"I go {sound}.");
        }
        public void Move(string move)
        {
            Console.WriteLine($"I {this.move} around the farm all day.");
        }
        public void Eat(string favSnack)
        {
            Console.WriteLine($"I like to eat {favSnack}.");
        }
        public void Weight(int avgWeight)
        {
            Console.WriteLine($"I usually weigh about {avgWeight}lbs.");
        }
      
    }
    //decide on four or more animals
    //for each animal decide on four or more methods
    public class Amphibian : Animal
    {
        string sound = "ribbit";
        string move = "hop";
        string favSnack = "flies";
        double avgWeight = .05d;

    }
    public class BullFrog : Amphibian 
    {
        double avgWeight = .375d;
    }

    public class Toad : Amphibian
    {
        double avgWeight = .175d;
    }
    

我在哪里 go 錯了? 當我調用方法時

BullFrog kermit = new BullFrog();
            kermit.Move(kermit.movement);
            kermit.Eat(kermit.favSnack);

我得到“我整天在農場”和兩個空白行作為 output。 我的問題是

檢查 C# 中的virtualoverride關鍵字。 如果您想實際更改派生的 class 的移動方式,則可以使用此選項。 Go 如果只是字符串更改,則使用構造函數方式。

public class Animal
{
     public virtual string move { get; set; }
public class Amphibian : Animal
{
     public override string move { get; set; } =  "hop";

你的線string move = "hop"; 只是在Amphibian class 中聲明了一個私有屬性,這不會以任何方式影響基礎 class。

另一種處理方法是在構造函數中設置值,但您應該記住始終在您正在創建的任何構造函數中設置值。

public class Animal
{
     public string move { get; set; }
 
     public Animal(string move) {
         this.move = move;
     }

接着

public class Amphibian : Animal
{
     public Amphibian(): base("hop") {
     }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM