如何使用Mono.CSharp.Evaluator编译委托?

时间:2014-07-28 00:17:30

标签: c# mono evaluator

我正在尝试编译一大块C代码并返回一个委托,我可以用它稍后调用代码。到目前为止我已经尝试了

eval.Compile("delegate () {}");

以及

eval.Evaluate("delegate () {}");

两种情况都给我同样的错误:

FatalException: Cannot convert `anonymous method' to non-delegate type `object'
Mono.CSharp.Report.Error (Int32 code, Location loc, System.String error)
Mono.CSharp.Report.Error (Int32 code, Location loc, System.String format, System.String arg1, System.String arg2)
Mono.CSharp.AnonymousMethodExpression.CompatibleChecks (Mono.CSharp.ResolveContext ec, Mono.CSharp.TypeSpec delegate_type)
Mono.CSharp.AnonymousMethodExpression.Compatible (Mono.CSharp.ResolveContext ec, Mono.CSharp.TypeSpec type)
Mono.CSharp.Convert.ImplicitConversionStandard (Mono.CSharp.ResolveContext ec, Mono.CSharp.Expression expr, Mono.CSharp.TypeSpec target_type, Location loc, Boolean explicit_cast)
Mono.CSharp.Convert.ImplicitConversionStandard (Mono.CSharp.ResolveContext ec, Mono.CSharp.Expression expr, Mono.CSharp.TypeSpec target_type, Location loc)
Mono.CSharp.Convert.ImplicitConversion (Mono.CSharp.ResolveContext ec, Mono.CSharp.Expression expr, Mono.CSharp.TypeSpec target_type, Location loc)
Mono.CSharp.Convert.ImplicitConversionRequired (Mono.CSharp.ResolveContext ec, Mono.CSharp.Expression source, Mono.CSharp.TypeSpec target_type, Location loc)
Mono.CSharp.Assign.ResolveConversions (Mono.CSharp.ResolveContext ec)
Mono.CSharp.Assign.DoResolve (Mono.CSharp.ResolveContext ec)
Mono.CSharp.SimpleAssign.DoResolve (Mono.CSharp.ResolveContext ec)
Mono.CSharp.OptionalAssign.DoResolve (Mono.CSharp.ResolveContext ec)
Mono.CSharp.Expression.Resolve (Mono.CSharp.ResolveContext ec, ResolveFlags flags)
Rethrow as InternalErrorException: (1,1): InteractiveHost
Mono.CSharp.Method.Emit ()
Mono.CSharp.TypeDefinition.Emit ()
Mono.CSharp.ClassOrStruct.Emit ()
Mono.CSharp.Class.Emit ()
Mono.CSharp.TypeDefinition.EmitContainer ()
Mono.CSharp.Evaluator.CompileBlock (Mono.CSharp.Class host, Mono.CSharp.Undo undo, Mono.CSharp.Report Report)
Mono.CSharp.Evaluator.Compile (System.String input, Mono.CSharp.CompiledMethod& compiled)
Mono.CSharp.Evaluator.Compile (System.String input)
DynamicMonoBehaviour.SetDynamicMethod (System.String methodname, System.String code, System.Type returnType) (at Assets/Kelvin4/DynamicMonoBehaviour.cs:53)
DynamicMonoBehaviour.Awake () (at Assets/Kelvin4/DynamicMonoBehaviour.cs:37)

1 个答案:

答案 0 :(得分:4)

匿名方法和lambda表达式是无类型表达式,不能单独存在。

您需要将其显式转换为委托类型,以使其成为对象:

new Action(delegate { ... })