c# - 如何在 C# 中按类型创建动态委托(delegate)对象?

标签 c# reflection delegates

假设我有一个 type,我知道它派生自 Delegate 类型。我想创建一个这种类型的对象,包装一个接受任意参数并返回正确返回类型的对象的匿名委托(delegate):

var retType = type.GetMethod("Invoke").ReturnType;
var obj = Delegate.CreateDelegate(type, delegate(object[] args) {
    ...
    if (retType != typeof(void))
      ... somehow create object of type retType and return it ...
});

显然这不会编译,因为 CreateDelegate 需要一个 MethodInfo 作为第二个参数。我怎样才能正确地做到这一点?

更新:关于我正在努力实现的目标的更多信息。有两个应用程序在运行——浏览器中的客户端和 C# 中的服务器。浏览器能够通过将参数序列化为 JSON 并通过网络发送调用(如在 RPC 中)来调用服务器端的远程函数。这已经有效,但我想添加对回调的支持。例如:

JavaScript(客户端):

function onNewObject(uuid) { console.log(uuid); }
server.notifyAboutNewObjects(onNewObject);

C#(服务器):

void notifyAboutNewObjects(Action<string> callback) {
  ...
  callback("new-object-uuid");
  ...
}

中间件代码将接收来自浏览器的调用,并且需要生成伪造的 callback 委托(delegate),该委托(delegate)实际上会将对 callback 的调用发送回浏览器并阻止线程直到完成。发送/接收的代码已经存在,我只是停留在如何生成一个通用委托(delegate)上,该委托(delegate)将简单地将所有参数放入一个数组并将它们传递给发送代码。

更新:如果有人可以编写将在运行时生成此类委托(delegate)的代码(例如使用 DynamicMethod ),我会认为这是一个有效的答案。我只是没有足够的时间来学习如何做到这一点,希望有经验的人能够足够快地编写这段代码。本质上,代码应该只接受任意委托(delegate)参数(列表和类型在运行时可用),将它们放入数组中并调用泛型方法。泛型方法将始终返回一个对象,如果函数返回void,则应将其转换为相应的返回类型或忽略。

更新:我已经创建了一个小测试程序来演示我需要什么:

using System;
using System.Reflection;

namespace TestDynamicDelegates
{
    class MainClass
    {
        // Test function, for which we need to create default parameters.
        private static string Foobar(float x, Action<int> a1, Func<string, string> a2) {
            a1(42);
            return a2("test");
        }

        // Delegate to represent generic function.
        private delegate object AnyFunc(params object[] args);

        // Construct a set of default parameters to be passed into a function.
        private static object[] ConstructParams(ParameterInfo[] paramInfos)
        {
            object[] methodParams = new object[paramInfos.Length];
            for (var i = 0; i < paramInfos.Length; i++) {
                ParameterInfo paramInfo = paramInfos[i];
                if (typeof(Delegate).IsAssignableFrom(paramInfo.ParameterType)) {
                    // For delegate types we create a delegate that maps onto a generic function.
                    Type retType = paramInfo.ParameterType.GetMethod("Invoke").ReturnType;

                    // Generic function that will simply print arguments and create default return value (or return null
                    // if return type is void).
                    AnyFunc tmpObj = delegate(object[] args) {
                        Console.WriteLine("Invoked dynamic delegate with following parameters:");
                        for (var j = 0; j < args.Length; j++)
                            Console.WriteLine("  {0}: {1}", j, args[j]);
                        if (retType != typeof(void))
                            return Activator.CreateInstance(retType);
                        return null;
                    };

                    // Convert generic function to the required delegate type.
                    methodParams[i] = /* somehow cast tmpObj into paramInfo.ParameterType */
                } else {
                    // For all other argument type we create a default value.
                    methodParams[i] = Activator.CreateInstance(paramInfo.ParameterType);
                }
            }

            return methodParams;
        }

        public static void Main(string[] args)
        {
            Delegate d = (Func<float, Action<int>,Func<string,string>,string>)Foobar;

            ParameterInfo[] paramInfo = d.Method.GetParameters();
            object[] methodParams = ConstructParams(paramInfo);
            Console.WriteLine("{0} returned: {1}", d.Method.Name, d.DynamicInvoke(methodParams));
        }
    }
}

最佳答案

我写了一个开源 PCL 库,叫做 Dynamitey (在 nuget 中),它使用 C# DLR 执行各种动态操作。 .

它特别有一个名为 Dynamic.CoerceToDelegate(object invokeableObject, Type delegateType) 的静态方法,它基本上包装了 DynamicObject 或更通用的委托(delegate)的动态调用,使用 CompiledExpressions ( source ) 的特定委托(delegate)类型。

使用 System.Dynamic 你可以创建一个可调用对象:

public class AnyInvokeObject:DynamicObject{
    Func<object[],object> _func;
    public AnyInvokeObject(Func<object[],object> func){
       _func = func;
    }
    public override bool TryInvoke(InvokeBinder binder, object[] args, out object result){
       result = _func(args);
       return true;
    }
}

然后在你的样本中:

var tmpObj = new AnyInvokeObject(args => {
                     Console.WriteLine("Invoked dynamic delegate with following parameters:");
                     for (var j = 0; j < args.Length; j++)
                         Console.WriteLine("  {0}: {1}", j, args[j]);
                     if (retType != typeof(void))
                         return Activator.CreateInstance(retType);
                     return null;
                });
methodParams[i] = Dynamic.CoerceToDelegate(tmpObj, paramInfo.ParameterType);

关于c# - 如何在 C# 中按类型创建动态委托(delegate)对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18687033/

相关文章:

c# - 提取对象类型以用作通用 <T>

c# - 如何在 C# 中获取有关委托(delegate)函数实例的信息(如名称或包含类)?

c# - 尝试 open() sql server 时出错

c# - 将 sql (row_number 和 DENSE_RANK) 转换为 linq

c# - 如何获得完整的关注者列表

c# - DataContract 序列化异常(数据契约名称不是预期的)

C# 以编程方式取消最小化表单

c# - 为什么 C# 中没有 `fieldof` 或 `methodof` 运算符?

Swift,对于一些 UIViews 在点击时到他们的整体 Controller

iOS AwesomeMenu 委派和叠加