gpt4 book ai didi

c# - 如何在 C# 中从字符串调用委托(delegate)?

转载 作者:行者123 更新时间:2023-11-30 19:32:04 24 4
gpt4 key购买 nike

是否可以通过变量名(作为字符串)调用存储在变量中的委托(delegate)?我想我必须使用反射机制,但我什么也得不到

示例代码:

class Demo {
public delegate int DemoDelegate();

private static int One() {
return 1;
}
private static void CallDelegate(string name) {
// somehow get the value of the variable with the name
// stored in "name" and call the delegate using reflection
}
private static void CallDelegate(string name, DemoDelegate d) {
d();
}
static void main(string[] args) {
DemoDelegate one = Demo.One;
CallDelegate(one);
// this works, but i want to avoid writing the name of the variable/delegate twice:
CallDelegate("one", one);
}

}

这可能吗?如果是这样怎么办?如果没有,那我只好用第二种形式了,运气不好

最佳答案

变量几乎不存在。可靠地按字符串调用(在这种情况下)的唯一方法是将委托(delegate)存储在字典中:

Dictionary<string, DemoDelegate> calls = new Dictionary<string, DemoDelegate>
{
{"one",one}, {"two",two}
}

现在将该字典存储在某处(通常是在一个字段中),然后执行如下操作:

private int CallDelegate(string name) {
return calls[name].Invoke(); // <==== args there if needed
}

关于c# - 如何在 C# 中从字符串调用委托(delegate)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6010555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com