将方法名称作为字符串传递并分配给委托

Pass method name as string and assign to delegate

我似乎无法快速将方法名称作为字符串传递并将其分配给委托。

我想要一个 class 从参数分配动态方法但不知道如何去做。

    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;


    }

如何传递表单名称和要调用的方法,然后将表单中的方法分配给委托?

你可以使用反射。下面的代码假定所讨论的方法总是只接受一个 string.

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

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

在 .Net 4.5 中,您可以使用 CallerMemberNameAttribute 获取调用方法的名称。我一直将其与 INotifyPropertyChanged 一起使用。这样我就可以这样写:

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

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