How to call delegate from string in C#?

半世苍凉 提交于 2019-12-22 16:53:47

问题


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

example 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


回答1:


Yes, it is possible, as long as you use Linq Expressions, and little reflection.

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();
        }
    }
}



回答2:


Variables barely exist. The only way to reliably call-by-string (in this scenario) would be to store the delegates in a dictionary:

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

Now store that dictionary somewhere (in a field, typically), and do something like:

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



回答3:


public void Fire(string name)
        {
            FieldInfo field = this.GetType().GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

            if (field != null)
            {
                Delegate method = field.GetValue(this) as Delegate;

                if (method != null)
                {
                    method.Method.Invoke(method.Target, new object[0]);
                }
            }
        }

Obviously restricts you from having parameterized delegates.




回答4:


You can't really access variables in another stack frame (although I think it is possible using hackery around the StackFrame class). Instead, you'll be wanting to pass an Delegate object around and use methods like DynamicInvoke, if you want to invoke a generalised delegate in a reflection-like manner.



来源:https://stackoverflow.com/questions/6010555/how-to-call-delegate-from-string-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!