C#从派生类访问父类的属性

时间:2018-08-08 15:21:55

标签: c#

我有一个名为PINPAD的类,一个名为Devices的基类以及两个名为DevADev B的派生类

问题在于,主类属性PINPAD.Status需要从类DevADevB进行更新

代码如下:

public class CALLER()
{
  CALLER()
  {
    PINPAD PINPD = new PINPAD("A");
    //....
    MessageBox.Show(PINPD.Status);
  }
}

public class PINPAD()
{
    public Devices MyDev = null;
    public string Status = "";

    public PINPAD(string Model)
    {
        if (Model = "A")
        {
            DevA MyDev = new DevA()
        }
        else
        {
            DevB MyDev = new DevB()
        }

        MyDev.DoWork();
    }
}

public class Devices
{
    public virtual void DoWork() {}
}

public class DevA : Devices
{
    public override void DoWork() { }

    DevA()
    {
        PINPAD.Status = "Broken";
        //Status not avialable!
    }
}

public class DevB : Devices
{
    public override void DoWork() { }

    DevB()
    {
        PINPAD.Status = "Working!";
        //Status not avialable!
    }
}

1 个答案:

答案 0 :(得分:0)

您已将PINPAD.Status声明为实例字段,这意味着您必须具有PINPAD类型的对象才能访问它。

var myPinpad = new PINPAD();
myPinpad.Status = "Whatever";

如果只希望一个字段随处可见,请声明字段static

public static string Status = "";