I have 2 forms and I want to call a function of Form1 defined in an interface from Form2. I tried using delegates and events. Is there a better way of doing this?
Form1
namespace atszodidb
{
public partial class Form1 : Form
{
}
}
interface db
{
void func(string param);
}
class db_veiksmai : db // veiksmai = actions
{
public db_veiksmai()
{
}
public void func(string param)
{
MessageBox.Show(param);
}
}
Form2
namespace atszodidb
{
public partial class Form2 : Form
{
void function()
{
}
{
}
How to call void func(string param) from function void function()? I tried to do this with a delegate:
Program.cs
public static class Data
{
public delegate void MyEvent(string data);
public static MyEvent EventHandler;
}
and in Form2
Data.EventHandler("lalalal");
However, I don’t know where to write Data.EventHandler = new Data.MyEvent(func);. I tried in the constructor of class db_veiksmai, but it’s a bad solution.
You need an instance of a class in order to call an instance method. So:
Or have your Form2 take the interface as a constructor dependency:
and now it will be the responsibility of the consumer of Form2 to pass a specific implementation of
dbwhen constructingForm2.Remark: in .NET as a convention interface names start with
I, anddbis a very poor name for an interface.