So I have the following:
public interface Client
{
void Operation1();
void Operation2();
}
public class Client1 : Client
{
public void Operation1()
{
Console.WriteLine("Client1 - Operation1");
}
public void Operation2()
{
Console.WriteLine("Client1 - Operation2");
}
}
public class Client2 : Client
{
public void Operation1()
{
Console.WriteLine("Client2 - Operation1");
}
public void Operation2()
{
Console.WriteLine("Client2 - Operation2");
}
}
public class Client3 : Client
{
public void Operation1()
{
Console.WriteLine("Client3 - Operation1");
}
public void Operation2()
{
Console.WriteLine("Client3 - Operation2");
}
}
I need a way to call a method of all the clients with a single call. Something like a delegate.
Basically I want to do the following: Clients.Operation1() Which outputs: Client1 - Operation1 Client2 - Operation1 Client3 - Operation1
One way to achieve this is to have the following class:
public class Clients : Client
{
public List<Client> Clients { get; set; }
public void Operation1()
{
foreach(Client c in Clients)
{
c.Operation1();
}
}
public void Operation2()
{
foreach (Client c in Clients)
{
c.Operation2();
}
}
}
but then whenever I change the Client interface, I will also have to change the Clients class. Is there some way to generate the Clients class(or something similar) dynamically?
Please let me know if you need a better explanation, because it is really hard for me to explain this question.
You can simply implement one method Execute and pass the method that you want execute to it:
public class Clients
{
public List<Client> ClientList { get; set; }
public void Execute(Action<Client> action)
{
ClientList.ForEach(action);
}
}
Usage:
new Clients().Execute(x => x.Operation1(someString, someInt));
new Clients().Execute(x => x.Operation2());
With this example you will not have to implement the interface in your Clients class and will not have to remaster it every time the interface changes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With