获取Func <t>变量的参数</t>

时间:2014-05-14 21:12:36

标签: c# dynamic lambda expression-trees func

我有一个相当复杂的问题。我试图从方法及其正式和实际参数中获取唯一键。该方法的目标是进行方法调用,并根据以下内容返回唯一键:1)类和方法的名称以及2)调用它的参数的名称和值。

该方法看起来像这样(对所有细节都很抱歉,但我找不到合理的方法让这个例子更小但仍然可以解释我的问题)

 public class MethodKey
    {
        public static string GetKey<T>(Expression<Func<T>> method, params string[] paramMembers)
        {
            var keys = new Dictionary<string, string>();
            string scope = null;
            string prefix = null;
            ParameterInfo[] formalParams = null;
            object[] actual = null;

            var methodCall = method.Body as MethodCallExpression;
            if (methodCall != null)
            {
                scope = methodCall.Method.DeclaringType.FullName;
                prefix = methodCall.Method.Name;

                IEnumerable<Expression> actualParams = methodCall.Arguments;
                actual = actualParams.Select(GetValueOfParameter<T>).ToArray();
                formalParams = methodCall.Method.GetParameters();
            }
            else
            {
                // TODO: Check if the supplied expression is something that makes sense to evaluate as a method, e.g. MemberExpression (method.Body as MemberExpression)

                var objectMember = Expression.Convert(method.Body, typeof (object));
                var getterLambda = Expression.Lambda<Func<object>>(objectMember);
                var getter = getterLambda.Compile();
                var m = getter();


                var m2 = ((System.Delegate) m);

                var delegateDeclaringType = m2.Method.DeclaringType;
                var actualMethodDeclaringType = delegateDeclaringType.DeclaringType;
                scope = actualMethodDeclaringType.FullName;
                var ar = m2.Target;
                formalParams = m2.Method.GetParameters();
                //var m = (System.MulticastDelegate)((Expression.Lambda<Func<object>>(Expression.Convert(method.Body, typeof(object)))).Compile()())

                //throw new ArgumentException("Caller is not a method", "method");
            }


            // null list of paramMembers should disregard all parameters when creating key.
            if (paramMembers != null)
            {
                for (var i = 0; i < formalParams.Length; i++)
                {
                    var par = formalParams[i];
                    // empty list of paramMembers should be treated as using all parameters 
                    if (paramMembers.Length == 0 || paramMembers.Contains(par.Name))
                    {
                        var value = actual[i];
                        keys.Add(par.Name, value.ToString());
                    }
                }

                if (paramMembers.Length != 0 && keys.Count != paramMembers.Length)
                {
                    var notFound = paramMembers.Where(x => !keys.ContainsKey(x));
                    var notFoundString = string.Join(", ", notFound);

                    throw new ArgumentException("Unable to find the following parameters in supplied method: " + notFoundString, "paramMembers");
                }
            }

            return scope + "¤" + prefix +  "¤" + Flatten(keys);

        }


        private static object GetValueOfParameter<T>(Expression parameter)
        {
            LambdaExpression lambda = Expression.Lambda(parameter);
            var compiledExpression = lambda.Compile();
            var value = compiledExpression.DynamicInvoke();
            return value;
        }
}

然后,我有以下测试,它可以正常工作:

        [Test]
        public void GetKey_From_Expression_Returns_Expected_Scope()
        {
            const string expectedScope = "MethodNameTests.DummyObject";
            var expected = expectedScope + "¤" + "SayHello" + "¤" + MethodKey.Flatten(new Dictionary<string, string>() { { "name", "Jens" } });

            var dummy = new DummyObject();

            var actual = MethodKey.GetKey(() => dummy.SayHello("Jens"), "name");

            Assert.That(actual, Is.Not.Null);
            Assert.That(actual, Is.EqualTo(expected));
        }

但是,如果我将() => dummy.SayHello("Jens")调用放入变量中,则调用失败。因为我不再在我的GetKey方法中获得MethodCallExpression,而是FieldExpressionMemberExpression的子类。测试是:

        [Test]
        public void GetKey_Works_With_func_variable()
        {
            const string expectedScope = "MethodNameTests.DummyObject";
            var expected = expectedScope + "¤" + "SayHello" + "¤" + MethodKey.Flatten(new Dictionary<string, string>() { { "name", "Jens" } });

            var dummy = new DummyObject();

            Func<string> indirection = (() => dummy.SayHello("Jens"));

            // This fails. I would like to do the following, but the compiler
            // doesn't agree :)
            // var actual = MethodKey.GetKey(indirection, "name");
            var actual = MethodKey.GetKey(() => indirection, "name");

            Assert.That(actual, Is.Not.Null);
            Assert.That(actual, Is.EqualTo(expected));
        }

DummySayHello方法定义很简单:

 public class DummyObject
    {
        public string SayHello(string name)
        {
            return "Hello " + name;
        }

        public string Meet(string person1, string person2 )
        {
            return person1 + " met " + person2;
        }
    }

我有两个问题:

  1. 有没有办法将变量indirection发送到MethodKey.GetKey,并将其作为MethodCallExpression类型获取?
  2. 如果没有,如果我得到MemberExpression,我怎样才能获得所提供方法的名称和价值?我在代码的“else”部分尝试了几个,但没有成功。
  3. 感谢任何帮助。

    提前致谢,对于这篇长篇文章感到抱歉。

1 个答案:

答案 0 :(得分:3)

问题是你把它放入了错误的变量类型。您的方法需要Expression<Func<T>>,并且您正在使用类型为Func<string>的变量来存储它。以下内容应解决您的问题:

Expression<Func<string>> foo = () => dummy.SayHello("Jens");
var actual = MethodKey.GetKey<string>(foo, "name");

converting a .net Func<T> to a .net Expression<Func<T>>讨论了FuncExpression<Func>之间的差异以及两者之间的转换,并且一眼就看出它没有。编译器将它们变成完全不同的东西。所以在编译时使它成为正确的东西,它应该工作正常。

如果这不是一个选项,那么可能是一个带Func而不是Expression的重载可能适合你。

请注意,在这两种情况下,我都会直接传递变量,而不是尝试将其变为调用中的新表达式。