簡體   English   中英

如何從基類執行方法時從某個類中獲取變量?

[英]How do I get a variable from a dervied class to be used when executing a method from a base class?

我正在嘗試使用從基類繼承的兩個不同的派生類,每個派生類都有一個與另一個不同的布爾變量。 boolean已在基類和派生類中分配。 但是,當我從僅在基類中聲明的派生類訪問方法時,布爾值會導致基類的結果。

我已經嘗試在每個初始化其聲明變量的類中執行一個方法。 沒有改變。

public partial class Form2 : Form
{
    public class BaseC : Form
    {
        public bool reversePlace = false;

        public void computeInput(BaseC cc)
        {
            if (reversePlace)
            {
                //Execute condition
                if (cc.reversePlace)
                {
                    //Execute execution from other derived class
                }
            }
        }
    }


    public class DerivedC1 : BaseC
    {
        public bool reversePlace = true;
    }

    public class DerivedC2 : BaseC
    {
        public bool reversePlace = false;
    }

    DerivedC1 C1 = new DerivedC1();
    DerivedC2 C2 = new DerivedC2();

    public Form2()
    {
        C1.computeInput(C2); //Should execute first condition for being true while ignoring the inner condtion for being false
    }

}

我應該從C1中途獲得一個if語句,同時跳過C2的if條件。 C1的布爾值應為true,而C2應為false。 然而,兩個布爾都被認為是假的。

使它成為虛擬財產。 當它被虛擬化並被覆蓋時,即使在基類中定義的代碼也會查看當前實例的被覆蓋最多的屬性。

public class BaseC : Form
{
    public virtual bool ReversePlace => false;
    //etc....
}


public class DerivedC1 : BaseC
{
    public override bool ReversePlace => true;
}

public class DerivedC2 : BaseC
{
    public override bool ReversePlace => false;
}

我需要一些時間來研究繼承,特別是虛擬屬性和方法,以及如何覆蓋它們。

您的基類通常應該在必要時使用關鍵字virtual和覆蓋子方法和類。

這是一個幫助您了解一般想法的鏈接: https//www.c-sharpcorner.com/UploadFile/3d39b4/virtual-method-in-C-Sharp/

如果您只想設置值,而不是從基類隱藏繼承的成員,則可以在構造函數中執行此操作。

...

public class DerivedC1 : BaseC
{
    public DerivedC1()
    {
        this.reversePlace = true;
    }
}

public class DerivedC2 : BaseC
{
    public DerivedC2()
    {
        this.reversePlace = false;
    }
}

...

暫無
暫無

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

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