C#在运行时创建参数类型未知的方法委托 [英] C# Create delegate of method where parameter types are unknown in runtime

查看:719
本文介绍了C#在运行时创建参数类型未知的方法委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是以下(我一定不知道是否可能);我知道运行时间类型。我知道在运行时我想要调用哪种方法。但是,我在编译时不知道。

What I am trying to do is the following (which I necessarily don't know if it's even possible); I know a run time type. I know which method I want to invoke in run time. However, I don't know this in compile time.

GetFunction方法将无法创建给定methodInfo的委托,因为inparam不是键入对象。

The GetFunction method won't be able to create a delegate of the given methodInfo since the inparam isn't of type object.

有没有办法创建一个函数的委托,我只知道我想委托的方法的Type和MethodInfo?

Is there a way to create a delegate of a function where I only know a Type and a MethodInfo of the method I wish to delegate?

public sealed class Functions {
    public static int SetStrValue(string s) {
        // set a string
    }

    public static int SetIntValue(int i) {
        // set an int
    }
}

public sealed class GetFunctions {
    public Func<object, int> GetFunction(Type type, MethodInfo methodInfo) {
        // what I would like to do.
        Func<object, int> func = Delegate.CreateDelegate(typeof(Func<object, int>), methodInfo);
        return t => func(t);
    }
}

public class InvokeFunctions {
    public void invokeFunction() {
        Type t = typeof(String);
        MethodInfo methodInfo = typeof(Functions).GetMethod("SetStrValue");
        int i = GetFunctions.GetFunction(t, methodInfo).Invoke("hello");
    }
}


推荐答案

你可以使用表达式树来创建委托。由于编译时间类型不知道,您可以尝试在运行时将参数转换为适当的类型。

You can use expression trees to create a delegate. As the compile time type is not known you could try to cast the parameter to the appropriate type at runtime.

public sealed class GetFunctions
{
    public static Func<object, int> GetFunction(MethodInfo methodInfo)
    {
        var obj = Expression.Parameter(typeof (object), "obj");
        var convert = Expression.Convert(obj, methodInfo.GetParameters().First().ParameterType);
        var call = Expression.Call(methodInfo, convert);
        var lambda = Expression.Lambda<Func<object, int>>(call, obj);

        return lambda.Compile();
    }
}

public class InvokeFunctions
{
    public void invokeFunction()
    {
        MethodInfo methodInfo = typeof(Functions).GetMethod("SetStrValue");
        int i = GetFunctions.GetFunction(methodInfo).Invoke("hello");

        MethodInfo methodInfo2 = typeof(Functions).GetMethod("SetIntValue");
        int i2 = GetFunctions.GetFunction(methodInfo2).Invoke(1);
    }
}

我已经删除了键入参数,并直接从Method的第一个参数中获取,如果这不是您可以改变的行为。

I've removed the Type parameter and taken it directly from Method's first parameter, If that's not the intended behavior you can change it.

这篇关于C#在运行时创建参数类型未知的方法委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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