如何获取派生方法来更改其基本变量或对象之一,然后从类外部调用更改的对象?

问题描述 投票:0回答:1

我正在尝试通过派生方法更改仅在基类中声明的变量/属性。结果总是从基本声明中收集赋值。

该值在基数中被赋值为false,我试图在派生方法中将其切换为true。当我从类外部调用派生变量时,它返回false。我已经尝试使用派生类作为通用参数来更改变量,但没有运气。

public class CPlayer : Hybrid
    {
        public TextBox inputTBox { get; set; }

        public CPlayer(TextBox InputTBox) : base(InputTBox)
        {
            inputTBox = InputTBox;
        }

        public void initiateStats()
        {
            proteinMeterMax = 125;
            proteinMeterCurrent = 125;
        }
    }

public class Hybrid
    {
        public TextBox inputTBox { get; set; }

        public bool stopOn = false;

        public Hybrid(TextBox InputTBox)
        {
            inputTBox = InputTBox;
        }

        public void runResult<T>(T hy) where T : Hybrid
        {
            hy.stopOn = true; //Trying either format to be certain.
            stopOn = true;
        }
    }


CPlayer cy = new CPlayer(inputBox);    

public void doSomething() {
cy.runResult(cy);

    if (cy.stopOn) {
        //I want something to happen when this is true. But it keeps returning false.
    }

}

该值必须为true,因此我可以遵循派生类之外的条件。尽管如此,它仍然是假的。

c# variables methods base derived
1个回答
0
投票

根据我的理解,我认为你想要覆盖一个属性或方法。然后,您需要指定关键字virtual以覆盖从基类到派生类的属性或方法

例如:

public class BaseClass
{
   public virtual bool stopOn {get;set;} = true;

   public virtual bool MethodName()
   {
       return stopOn;
   }
}

public class DerivedClass : BaseClass
{
   public override bool stopOn = false; // For property

   public override bool MethodName()  // For method
   {
       return stopOn;
   }
}

在我的情况下,您可以直接更改Base属性值而不覆盖:

public class BaseClass
{
   public virtual bool stopOn {get;set;} = true;
}

public class DerivedClass : BaseClass
{
    public DerivedClass(){
             stopOn = false;
    }
}

如果要在派生类中更改方法/函数行为,则应该重写它。

© www.soinside.com 2019 - 2024. All rights reserved.