如何从字符串在C#中调用的委托? [英] How to call delegate from string in C#?
本文介绍了如何从字符串在C#中调用的委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是它可以调用它的变量名存储在一个变量委托(字符串)?我想我不得不使用反射机制,但我没有得到任何地方
is it possible to call a delegate stored in a variable by its variable name (as a string)? i guess i'd have to use reflection mechanism, but i'm not getting anywhere
例如code:
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);
}
}
这甚至可能吗?如果是的话怎么样?如果没有,那么我必须使用第二种形式,运气不好
is this even possible? if so how? if not, then i have to use the second form, bad luck
推荐答案
是的,这是可能的,只要你使用Linq防爆pressions,并用心体会。
Yes, it is possible, as long as you use Linq Expressions, and little reflection.
看看这个code,它做一些事情呈三角什么,我想你想要的:
Take a look at this code, it does something simillar to what I think you want:
using System;
using System.Linq.Expressions;
using System.Reflection;
using System.Collections.Generic;
namespace q6010555
{
class Demo
{
static List<string> varNamesUsed = new List<string>();
public delegate int DemoDelegate();
private static int One()
{
return 1;
}
private static void CallDelegate(Expression<Func<DemoDelegate>> expr)
{
var lambda = expr as LambdaExpression;
var body = lambda.Body;
var field = body as MemberExpression;
var name = field.Member.Name;
var constant = field.Expression as ConstantExpression;
var value = (DemoDelegate)((field.Member as FieldInfo).GetValue(constant.Value));
// now you have the variable name... you may use it somehow!
// You could log the variable name.
varNamesUsed.Add(name);
value();
}
static void Main(string[] args)
{
DemoDelegate one = Demo.One;
CallDelegate(() => one);
// show used variable names
foreach (var item in varNamesUsed)
Console.WriteLine(item);
Console.ReadKey();
}
}
}
这篇关于如何从字符串在C#中调用的委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文