在Mono.Csharp脚本中,Lambda中的变量不起作用

时间:2015-11-07 02:45:43

标签: c# mono

发生Mono.Csharp.InternalError异常。 InnerException基本上表示没有设置对象引用。有什么想法吗?使用的代码:

using System;
using System.IO;
using Mono.CSharp;
using System.Reflection;
using System.Collections.Generic;

namespace TestMonoCSharp
{
    public class testmodel
    {
        public string a {get;set;}
        public double b {get;set;}
    }

    class MainClass
    {
        public static void Main (string[] args)
        {
            var tw = new StreamWriter(new MemoryStream());
            tw.AutoFlush = true;
            CompilerContext c = new CompilerContext(new CompilerSettings(), new StreamReportPrinter(tw));
            var csc = new Evaluator(c);
            csc.ReferenceAssembly(Assembly.GetExecutingAssembly());
            csc.Run("using System;");
            csc.Run("using System.Linq;");
            csc.Run("using System.Collections.Generic;");
            csc.Run("using TestMonoCSharp;");

            var query = @"new System.Func<IEnumerable<testmodel>, IEnumerable<testmodel>>((pos) => 
                        {
                            var avg = pos.Average(x=>x.b);
                            //return pos.Where(x=>x.b < 3 ).ToArray(); //works
                            return pos.Where(x=>x.b < avg ).ToArray(); //doesn't work
                        });";

            var list = new List<testmodel> () {new testmodel{ a = "a", b = 3}, new testmodel{ a = "a", b = 2} };
            var func = csc.Evaluate(query) as Func<IEnumerable<testmodel>, IEnumerable<testmodel>>;            
            var val  = func(list);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您正在尝试评估Delegate ...

new System.Func<IEnumerable<string>, IEnumerable<string>>((pos) =>                         {
   var avg = pos.Average(x=>x.Length);
   return pos.Where(x=>x.Length < avg ).ToArray(); //doesn't work
});

这导致mcs编译器中的内部System.NullReferenceException,因为没有任何上下文可以动态评估该语句的执行情况。

将其剪切/粘贴到Mono的csharp repl:

public class testmodel
    {
        public string a {get;set;}
        public double b {get;set;}
    }
testmodel[] list = {new testmodel{a="1",b=1}, new testmodel{a="22",b=2}, new testmodel{a="333",b=3}, new testmodel{a="4444",b=4}, new testmodel{a="55555", b=5}}
var averageEvaluator = new System.Func<IEnumerable<testmodel>, IEnumerable<testmodel>>((pos) =>                         {
   var avg = pos.Average(x=>x.b);
   return pos.Where(x=>x.b < avg ).ToArray();
})
var results = averageEvaluator(list)
foreach(var x in results){ print(x.a);}