How delegates work (in the background)?

前端 未结 6 554
温柔的废话
温柔的废话 2020-12-10 06:16

How do delegates work in c# behind the scenes and how can they be used efficiently?

EDIT: I know how they work on the surface(they are basically function pointers a

6条回答
  •  时光说笑
    2020-12-10 06:41

    Re efficiency - it isn't clear what you mean, but they can be used to achieve efficiency, by avoiding expensive reflection. For example, by using Delegate.CreateDelegate to create a (typed) pre-checked delegate to a dynamic/looked-up method, rather than using the (slower) MethodInfo.Invoke.

    For a trivial example (accessing the static T Parse(string) pattern for a type), see below. Note that it only uses reflection once (per type), rather than lots of times. This should out-perform either reflection or typical TypeConverter usage:

    using System;
    using System.Reflection;
    static class Program { // formatted for space
        static void Main() {
            // do this in a loop to see benefit...
            int i = Test.Parse("123");
            float f = Test.Parse("123.45");
        }
    }
    static class Test {
        public static T Parse(string text) { return parse(text); }
        static readonly Func parse;
        static Test() {
            try {
                MethodInfo method = typeof(T).GetMethod("Parse",
                    BindingFlags.Public | BindingFlags.Static,
                    null, new Type[] { typeof(string) }, null);
                parse = (Func) Delegate.CreateDelegate(
                    typeof(Func), method);
            } catch (Exception ex) {
                string msg = ex.Message;
                parse = delegate { throw new NotSupportedException(msg); };
            }
        }
    }
    

提交回复
热议问题