I am creating a generic class that will control all the DataGridView of my project, but a problem has arisen. I don't know how to call a function from an object type parameter.
FormTest
Form_Load(object sender, EventArgs e)
{
//Paso una referencia del DataGriView y
//Una referencia del fromulario
_dgvm = new DGVManager(ref dgvCBD, this);
}
//Función a Invocar
public void Saludar()
{
MessageBox.Show("Saludos desde prueba :)");
}
handler
internal class DGVManager
{
private DataGridView _dgv;
private MethodInvoker Saludar;
public DGVManager(ref DataGridView dgv, object instancia)
{
this._dgv = dgv;
Saludar = instancia.GetMethod("Saludar"); //error
Saludar.Invoke(instancia);
}
}
I don't have much experience with object type parameters, I hope someone can help me, Greetings.
Instead of using reflection, which is not very solid, because your code can change, and only at runtime will you realize if the method
Saludar
does not exist, ... it is better to define an interface like this:Then, you make sure that all your forms implement this interface. So the code that needs to execute a method of the instance can do it like this (I removed the
ref
, by the way, I don't see that you need it):Another option, which may not be as good as the one above in my opinion, but is still better than using reflection, is to use function delegates . In that case, you wouldn't need an interface. You would just have to adjust the parameter so that it receives a reference to the method
Saludar
, instead of receiving a reference to the form itself:And this would be the code to pass the reference to the method
Saludar
: