c# - 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));
解决方案
经过多次研究,我找到了另一种解决此问题的方法。将函数名称保存为字符串而不是 Action 或委托
然后使用System.Reflection.MethodInfo
并btn.AddHandler
使用它。
通过这种方式,该功能必须是公共的。
推荐阅读
- python - 如何修复石头剪刀布中的计算机选择
- javascript - threejs几何三角形旋转不居中
- python - 从 tkinter filedialog 返回文件的文件路径
- php - 检查电报登录的输入
- javascript - 即使用户存在于 nodejs 应用程序的 mongodb 中,model.findOne() 也会返回 null
- visual-c++ - 使用互斥锁或原子是否需要在线程启动时进行特殊处理?
- google-app-engine - “gcloud ml language analyze-sentiment”从 Python 客户端 analyze_sentiment 返回不同的结果
- jsf - 如何防止表单在同一html页面中提交时重置其他表单
- python - sublime 命令错误地使用了转义字符
- c++ - 如何将字符串转换为具有一定精度的双精度?