I have some interface:
interface IServerListener
{
void onServerStarted();
void onSessionStarted();
void onSessionCompleted(List<string> data);
}
And there is some method, which gets an instance of that interface for executing methods:
public void start(IServerListener listener)
{
IPEndPoint hostPoint = new IPEndPoint(IPAddress.Parse(getLocalHost()), PORT);
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(hostPoint);
serverSocket.Listen(5);
listener.onServerStarted(); //Calling
while(true)...
}
When I execute this method (start) from the main form class, I want to pass into parameters exactly the anonymous class that implements this interface to have access to use form elements:
private void Form1_Load(object sender, EventArgs e)
{
server = new Server();
server.start(new IServerListener()
{
void onServerStarted()
{
rtxtOutput.AppendText("Started... ");
}
void onSessionCompleted(List<string> data)
{
rtxtOutput.AppendText("Session completed: " + String.Join(", ", data));
}
void onSessionStarted()
{
rtxtOutput.AppendText("New session started... ");
}
});
}
But I can't do it the way I did it in Java. I get the following message:
Cannot create an instance of the abstract class or interface 'IServerListener'
So I tried to create separate class that implement this interface and already there to do what I need. But I can't to get access to use form elements from there:
private class AnonymousIServerListener : IServerListener
{
public void onServerStarted()
{
rtxtOutput.AppendText("Started... ");
//The name 'rtxtOutput' does not exist in the current context
}
public void onSessionCompleted(List<string> data)
{
rtxtOutput.AppendText("Session completed: " + String.Join(", ", data));
//The name 'rtxtOutput' does not exist in the current context
}
public void onSessionStarted()
{
rtxtOutput.AppendText("New session started... ");
//The name 'rtxtOutput' does not exist in the current context
}
}
Please tell me what to do in this case without crutches. Is it possible to use an anonymous class in C# in general? If not, what to do in this case?
Thanks in advance. Regards...