Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
125 views
in Technique[技术] by (71.8m points)

c# - How delegates work (in the background)?

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 and allow callback methods with certain signatures to be invoked using their address). What I need to know is how the CLR actually implements them internally. What exactly happens behind the scenes when you define a delegate and when you invoke a callback method using the delegate object?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<int>.Parse("123");
        float f = Test<float>.Parse("123.45");
    }
}
static class Test<T> {
    public static T Parse(string text) { return parse(text); }
    static readonly Func<string, T> parse;
    static Test() {
        try {
            MethodInfo method = typeof(T).GetMethod("Parse",
                BindingFlags.Public | BindingFlags.Static,
                null, new Type[] { typeof(string) }, null);
            parse = (Func<string, T>) Delegate.CreateDelegate(
                typeof(Func<string, T>), method);
        } catch (Exception ex) {
            string msg = ex.Message;
            parse = delegate { throw new NotSupportedException(msg); };
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...