【发布时间】:2011-05-15 19:05:49
【问题描述】:
是否可以通过变量名(作为字符串)调用存储在变量中的委托?我想我必须使用反射机制,但我没有得到任何地方
示例代码:
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);
}
}
这甚至可能吗?如果是这样怎么办?如果没有,那我只能用第二种形式了,倒霉
【问题讨论】:
-
在第二个重载中使用
DemoDelegate d完全违背了string name的目的,不是吗? -
@boltclock: 是的,这就是我想避免它的原因(在我的真实代码中,我想稍后将变量的名称存储到
Console.Out.WriteLine()) -
这里有许多基本错误。
One()是一个实例方法,您正在从静态方法中访问this。你想打什么电话?实例方法One()或存储在main()、one的局部变量中的委托? -
@knittl 如果您只想存储变量的名称,为什么不直接使用“this.delegateMember.Method.Name”?这对我来说比做狡猾的反射黑客更有意义?
-
@jeff:感谢提及,已修复。我想调用存储在局部变量“one”(小写)中的委托
标签: c# .net string reflection delegates