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

时间:2015-03-04 14:10:38

标签: c# delegates

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

我希望有一个类从参数中指定一个动态方法,但不能弄清楚如何操作。

    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;


    }

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

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

您可以使用反射。以下代码假定所讨论的方法始终只使用一个string类型的参数。

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

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

答案 2 :(得分:1)

在.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