[英]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. 该值在基数中被赋值为false,我试图在派生方法中将其切换为true。 When I call the derived variable from outside the classes though, it returns as false.
当我从类外部调用派生变量时,它返回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. 该值必须为true,因此我可以遵循派生类之外的条件。 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
然后,您需要指定关键字virtual以覆盖从基类到派生类的属性或方法
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: 在我的情况下,您可以直接更改Base属性值而不覆盖:
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. 如果要在派生类中更改方法/函数行为,则应该重写它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.