如何将多行的lambda语句字符串解析为DynamicExpression.ParseLambda?

时间:2018-03-28 14:28:13

标签: c# parsing dynamic lambda expression

我想将一个多语句lambda字符串(实际上是一个小程序)传递给DynamicExpression.ParseLambda,但我担心我可能已达到其局限性。我已经编写了代码来提供小型lambda表达式,但我认为它会阻塞整个程序。

到目前为止,这是MCVE。它显示了原始算法BuildSieve(),并且它还显示了lambda等效的开头,但它在第一行失败,异常为Unknown identifier 'long'

using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using diag=System.Diagnostics;
using myAlias = System.Linq.Dynamic;   //install package 'System.Linq.Dynamic' v.1.0.7 with NuGet

namespace LambdaStatement
{
    class Program
    {

        static void Main(string[] args)
        {

            BuildSieveLambda();

            Console.ReadKey();
        }

        static void BuildSieveLambda()
        {
            try
            {
                var pList = new List<ParameterExpression>();
                pList.Add(Expression.Parameter(typeof(int), "x"));
                LambdaExpression e = myAlias.DynamicExpression.ParseLambda(pList.ToArray(), null, "long n = 2000000;");
            }
            catch (Exception ex)
            {
                string msg = GetExMessage(ex);
                diag.Debug.WriteLine("DEBUGME: " + msg);
                throw new Exception(msg);

            }
        }

        public static string GetExMessage(Exception ex)
        {
            string ret = ex.Message;
            if (ex.InnerException!=null)
            {
                ret= ret+ ": " + GetExMessage(ex.InnerException);
            }
            return ret;
        }


        static void BuildSieve()
        {

            //https://gist.github.com/gideondsouza/1978926  Sieve of Eratosthenes C# implementation by code Gideon Israel Dsouza

            long n = 2000000;
            bool[] e = new bool[n];//by default they're all false
            for (int i = 2; i < n; i++)
            {
                e[i] = true;//set all numbers to true
            }
            //weed out the non primes by finding mutiples 
            for (int j = 2; j < n; j++)
            {
                if (e[j])//is true
                {
                    for (long p = 2; (p * j) < n; p++)
                    {
                        e[p * j] = false;
                    }
                }
            }

        }

您可能认为这是不可能的,但我在C#代码中看到了一些非常复杂的lambda表达式,实际上是完整的方法实现。因此,如果C#编译器或Visual Studio可以执行此操作,那么程序员是否可以访问该API?

1 个答案:

答案 0 :(得分:0)

您需要像添加n一样添加x

pList.Add(Expression.Parameter(typeof(long), "n"));
LamdaExpression e = myAlias.DynamicExpression.ParseLamda(pList.ToArray(), null, "n = 200000");

虽然,我承认,我不知道这个程序做了什么,但这就是你得到那个错误的原因。它将字符串中的long读作标识符,而不是类型。