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?
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);
}
}
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:
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:
public partial class Form2 : Form
{
void function()
{
db_veiksmai mydb = new db_veiksmai();
mydb.func("some parameter");
}
}
Or have your Form2 take the interface as a constructor dependency:
public partial class Form2 : Form
{
private readonly db _mydb;
public Form2(db mydb)
{
_mydb = mydb;
}
void function()
{
_mydb.func("some parameter");
}
}
and now it will be the responsibility of the consumer of Form2 to pass a specific implementation of db
when constructing Form2
.
Remark: in .NET as a convention interface names start with I
, and db
is a very poor name for an interface.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.