首页 > 解决方案 > Func 作为类中的变量

问题描述

我想使用一个函数作为我分配的变量。

像这样的东西

班级:

public class Func
{
    public string Name { get; set; }
    public string Content { get; set; }
    public Function function { get; set; } //Not sure what type for a func
}

功能:

public void Click_Event(object sender,EventArgs e)
{
//Some code here.
}

分配函数的列表:

List<Func> funcList = new List<Func>();
Func func = new Func();
func.Name = "Name";
func.Content = "Hello World";
func.function = Click_Event;  //This is what I really want to do.
funcList.Add(func);

有没有办法做到这一点?

已编辑

下面的一些评论说反射可能会导致性能问题,但我使用它并且目前没有看到任何缓慢的问题。我只在第一次启动应用程序时使用它。

这是我使用它的示例代码。

MethodInfo method = this.GetType().GetMethod("FuncName"); //Or using nameof
btnFunc.AddHandler(Button.ClickEvent, Delegate.CreateDelegate(Button.ClickEvent.HandlerType, this, method, false));

标签: c#

解决方案


经过多次研究,我找到了另一种解决此问题的方法。将函数名称保存为字符串而不是 Action 或委托

然后使用System.Reflection.MethodInfobtn.AddHandler使用它。

通过这种方式,该功能必须是公共的。


推荐阅读