代表们是如何工作的(背景)? [英] How delegates work (in the background)?

查看:64
本文介绍了代表们是如何工作的(背景)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何代表们在幕后C#工作,如何对它们进行有效的利用?

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

编辑:我知道他们在表面上是如何工作的(他们基本上是函数指针,并允许使用他们的地址,被调用某些签名的回调方法)。我需要知道的是CLR如何实际内部实现它们。到底发生了什么幕后当你定义了一个代理,当你使用委托对象调用的回调方法?

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?

推荐答案

重效率 - 目前尚不清楚你的意思,但它们可以被用来实现的效率,避免昂贵的反思。例如,通过使用 Delegate.CreateDelegate 以创建一个(类型)pre-检查委托动态/看向上的方法,而不是使用(慢) MethodInfo.Invoke

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.

对于一个简单的例子(访问静态 T解析(字符串)模式的类型),见下文。需要注意的是它仅使用反射一次(每个类型),而不是大量的倍。这应该在性能无论是反射或典型的TypeConverter 用法:

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

这篇关于代表们是如何工作的(背景)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆