簡體   English   中英

Mono.Csharp腳本中的Lambda內部無法使用變量

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM