简体   繁体   中英

How do I get a derived method to change one of its base variables or objects and then call the changed object from outside the class?

I'm trying to change a variable/property declared only in the base class through a derived method. The result always gathers the assignment from the base declaration however.

The value is assigned false in the base and I am attempting to switch it to true in a derived method. When I call the derived variable from outside the classes though, it returns as false. I already tried altering the variable using the derived class as a generic parameter, but no luck.

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.
    }

}

This value needs to be true so I can follow conditions outside the derived class. It keeps returning false though.

In my understanding, I think you want to override a property or method right. Then, you need to specify a keyword virtual to override a property or method from base class to derived class

For Example:

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;
   }
}

In my case you can change Base property value directly without overriding:

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

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

If you want to change methods/functions behavior in derived class you should need to override that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM