So I have abstract class
public abstract class Client
{
public abstract void Send();
public abstract void Get();
}
And now there are 2 classes that inherit from Client
public class ClientV2 : Client
{
public string Value1 {get;set;}
//implement Send and Get method()
}
public class ClientV3 : Client
{
public string Value2 {get;set;}
public string Value3 {get;set;}
//implement Send and Get method()
}
For simplicity, Program class is general GUI class. Now when someone will click on checkbox a new object will be instantiated but also new controls will show, for example text box for Value 2. What I need to do is set a Value2 when someone will type something but since I am using abstract type I can't access that value, what do you think will be the best solution here?
public class Program
{
private Client client;
public void Client2CheckboxChecked()
{
client = new Client2();
}
public void Client2CheckboxChecked()
{
client = new Client3();
}
public void Value2Changed(string newValue)
{
//Here I would need to set Value2 propertyu of a ClientV3 using client
}
public void SendData()
{
client.Send();
}
}
I can of course create a different type for client 2 and client 3 that is rather than
private Client client;
I would have
private ClientV3 clientV2;
private ClientV3 clientV3;
But in a future there could also be a possibility for clientV4 and I want to minimize the amount of changes I would need to change in my Program class.
CodePudding user response:
you may create an abstract method SetValue
that all the different clients must implement and where the actual logic is in. Then in your Program.Value2Changed
just call that method:
public void Value2Changed(string newValue)
{
client.SetValue(newValue); // may be ClientV2 or ClientV3 or whatever
}
class Client
{
public abstract void SetValue(string newValue);
}
class ClientV2 : Client
{
public override void SetValue(string newValue) => this.Value2 = newValue;
}
class ClientV3 : Client
{
public override void SetValue(string newValue) => this.Value3 = newValue;
}
This delegates the task of setting the values from your Program
to the Client
.
CodePudding user response:
Since the parents cannot know what is in the inherited classes you can solve this problem with Downcasting
public void Value2Changed(string newValue)
{
(ClientV3)client.Value2 = newValue;
}