摆脱动作&LT参数; T> [英] Get Parameters from Action<T>

查看:164
本文介绍了摆脱动作&LT参数; T>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何传递到一个参数动作< T> ?该代码示例应该突出什么,我想要的目的。遗憾的是,这是一个有点长。

How do I get the parameters passed into an Action<T> ? The code example should highlight what I'm trying to achieve. Sorry that it's a little bit long.

class Program
{
    static void Main(string[] args)
    {
        Foo foo = new Foo();
        foo.GetParams(x => x.Bar(7, "hello"));
    }
}

class Foo
{
    public void Bar(int val, string thing) { }
}

static class Ex
{
    public static object[] GetParams<T>(this T obj, Action<T> action)
    {
        // Return new object[]{7, "hello"}
    }
}

唯一看起来依稀有用的选项是GetInvocationList()方法和目标。但他们都不包含(我认为这是因为我已经声明了行动的方式)后,我的数据。谢谢

The only options that look vaguely useful are GetInvocationList(), Method and Target. But none of them seem to contain the data I'm after (I think it's because of the way I've declared the Action). Thanks

编辑:这不是我想要的类型,它的实际值 - 在代码的注释位指出

It's not the types I want, it's the actual values - as noted in the commented bit of code.

推荐答案

要做到这一点,它实际上应该是表达<作用< T>> 。然后,它是分解表达的情况下。幸运的是我有所有的代码在上protobuf网,的here - 尤其是 ResolveMethod ,返回退出数组中的值(后走任何捕获变量等)。

To do that, it should actually be an Expression<Action<T>>. Then it is a case of decomposing the expression. Fortunately I have all the code for that over in protobuf-net, here - in particular ResolveMethod, which returns the values in the out array (after walking any captured variables, etc).

订立后的 ResolveMethod 公众(和删除所有的上方 ResolveMethod ),代码就是:

After making ResolveMethod public (and removing everything above ResolveMethod), the code is just:

public static object[] GetParams<T>(this T obj, Expression<Action<T>> action)
{
    Action ignoreThis;
    object[] args;
    ProtoClientExtensions.ResolveMethod<T>(action, out ignoreThis, out args);
    return args;
}

这篇关于摆脱动作&LT参数; T&GT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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