user2024839
user2024839

Reputation:

Pass method name as string and assign to delegate

I seem to be going no-where fast with passing a method name as a string and assigning it to a delegate.

I want to have a class that assigns a dynamic method from a parameter but can't work out how to do it.

    private delegate void ProgressMsg(string msg);
    private ProgressMsg AddMsg;

    public Progress(string FormName, string AddMsgMethodName, bool close, bool hide)
    {
        // set properties
        this.Hide = hide;
        this.Close = close;

        // Open form if not open
        this.Frm = Application.OpenForms[FormName];
        if (this.Frm == null)
        {
            // instatiate form
            this.Frm = (Form)Assembly.GetExecutingAssembly().CreateInstance(Assembly.GetExecutingAssembly().GetName().Name + "." + FormName);

            // show form
            this.Frm.Show();
        }

        // assign delegate
        this.AddMsg = new ProgressMsg(AddMsgMethodName);

        // Hide form
        this.Frm.Visible = !Hide;


    }

How can I pass the name of a form, and the method to call and then assign to the delegate the method from the form?

Upvotes: 1

Views: 2895

Answers (3)

Robert S.
Robert S.

Reputation: 2042

this.AddMsg = (ProgressMsg)Delegate.CreateDelegate(typeof(ProgressMsg), this.Frm, AddMsgMethodName);

Upvotes: 4

user2023861
user2023861

Reputation: 8208

In .Net 4.5 you can use the CallerMemberNameAttribute to get the name of the calling method. I use this all the time with INotifyPropertyChanged. This way I can write this:

private string _name;
public string Name
{
    get { return this._name; }
    set
    {
        if (this._name != value)
        {
            this._name = value;
            this.OnPropertyChanged(); //no argument passed
        }
    }
}

public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberNameAttribute]string propertyName = "")
{ //propertyName will be set to "Name"
    if (this.PropertyChanged != null)
        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}

See here for more

Upvotes: 2

Heinzi
Heinzi

Reputation: 172280

You can use reflection. The following code assumes that the method in question always takes exactly one parameter of type string.

var method = this.Frm.GetType().GetMethod(AddMsgMethodName,
      new Type[] { typeof(string) });

this.AddMsg = (ProgressMsg)Delegate.CreateDelegate(typeof(ProgressMsg), this.Frm, method);

Upvotes: 1

Related Questions