[英]variables not working inside Lambdas in Mono.Csharp script
引发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);
}
}
}
您正在尝试评估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);}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.