Invoke?

  • Thread starter Thread starter C# Learner
  • Start date Start date
C

C# Learner

How can I "invoke" a method containing parameters? I've tried
creating my own delegates and using them to do it, but can't get it
working. Can't find any info on this anywhere.

e.g.:

public class MainForm : Form
{

private delegate void D(char c);

private void Invoker()
{
D d = new D();
this.Invoke(d('t'));
}

private void Invokee(char c)
{
this.Text += c;
}

}
 
The thing is that Invoke only takes a delegate with no parameters as a parameter so the parameters that you need will have to be passed in an indirect manner. You could use a class for wrapping up the variables

public class InvokeHelpe

private char c
private Form form

public InvokeHelper(char c,Form form

this.c = c
this.form = form


public Invokee(

form.Text += c



public class MainForm : For


private delegate void D()

private void Invoker(

InvokeHelpher ih = new InvokeHelper('t',this)
D d = new D(ih.Invokee)
this.Invoke(d)





----- C# Learner wrote: ----

How can I "invoke" a method containing parameters? I've trie
creating my own delegates and using them to do it, but can't get i
working. Can't find any info on this anywhere

e.g.

public class MainForm : For


private delegate void D(char c)

private void Invoker(

D d = new D()
this.Invoke(d('t'))


private void Invokee(char c

this.Text += c
 
Sijin Joseph said:
The thing is that Invoke only takes a delegate with no parameters as a parameter so the parameters that you need will have
to be passed in an indirect manner. You could use a class for wrapping up the variables.

Ah... the joys of object-oriented programming! :-)

Thanks.
 
C# Learner said:
How can I "invoke" a method containing parameters?

Use the form of Invoke which takes two parameters - the first is the
delegate to invoke, the second is the parameter list (as an object
array). Here's a short but complete example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class MainForm : Form
{
delegate void D(char c);

MainForm()
{
SuspendLayout();

Size = new Size (200, 80);
Location = new Point (100, 100);

Button b = new Button();
b.Location = new Point (50, 20);
b.Size = new Size(100, 20);
b.Text = "Click me";
b.Click += new EventHandler (ButtonClicked);
Controls.Add(b);

ResumeLayout();
}

void ButtonClicked (object sender, EventArgs e)
{
D d = new D(Invokee);
Invoke (d, new object[]{'x'});
}

static void Main()
{
Application.Run (new MainForm());
}

void Invokee(char c)
{
this.Text += c;
}
}
 
Jon Skeet said:
Use the form of Invoke which takes two parameters - the first is the
delegate to invoke, the second is the parameter list (as an object
array). Here's a short but complete example:

<snip>

Thanks.
 
Back
Top