簡體   English   中英

C#中的繼承變量

[英]Inheritance variables in c#

為了練習,我試圖編寫一個計算器程序。 為了解決這個問題,我嘗試使用一些我已經學過但沒有真正使用過的高級繼承主題。 假設您有一個名為IMath的接口,其中包含一個方法string DoMath() 是否可以在IMath接口中編寫一個變量,以使實現該接口的所有類都可以看到新值? 因此,例如,我的課Add : IMath將有法DoMath()並在DoMath()方法會改變變量的值double ITotal它實現了IMath接口的所有類將看到新的價值。

您不能在接口中指定變量或字段,只能指定:

  • 方法
  • 性質
  • 索引器
  • 大事記

有關更多信息,請參見接口上的C#文檔

接口決定了預期的行為,但沒有決定預期的實現。 屬性可以理解為“檢索X值的能力”或“提供X值的能力”,其中變量為“存儲X的能力”。 這不是一回事,接口不能保證這一點。

如果絕對需要強制存在變量,則應使用基類。 我可能會考慮將這些東西結合起來,為外部接口使用接口(即計算器的功能如何)以及基類和繼承,以避免一遍又一遍地重寫相同的代碼。

聽起來您正在尋找的是抽象基類。

您所描述的內容的一種可能實現如下所示。

public abstract class MathBase
{
    public double Total { get; protected set; }

    public abstract string DoMath(double value);

    protected double ParseValue(string value)
    {
        double parsedValue;

        if (!double.TryParse(value, out parsedValue))
        {
            throw new ArgumentException(string.Format("The value '{0}' is not a number.", value), "value");
        }

        return parsedValue;
    }
}

public class Add : MathBase
{
    public override string DoMath(string value)
    {
        Total += ParseValue(value);

        return Convert.ToString(Total);
    }
}

如果希望從MathBase繼承的每個類的每個實例共享相同的Total值,則可以將其聲明為static

public abstract class MathBase
{
    public static double Total { get; protected set; }

    public abstract string DoMath(string value);
}

(盡管我不太確定您為什么要這么做)

您可以執行以下操作:

interface IMath
{
    string DoMath();
}

abstract class MathBase : IMath
{
    protected double Total { get; set; }

    public abstract string DoMath();
}

class Add : MathBase
{
    public override string DoMath()
    {
        this.Total = 2;

        return "2";
    }
}

暫無
暫無

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

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