Compile and run dynamic code, without generating EXE?

后端 未结 8 1776
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 14:17

I was wondering if it was possible to compile, and run stored code, without generating an exe or any type of other files, basically run the file from memory.

Basical

相关标签:
8条回答
  • 2020-11-27 14:49

    In Mono you use CSharp.Evaluator. It works truly in memory v. some of the other solutions mentioned that write out and read back in a file under the hood.

    0 讨论(0)
  • 2020-11-27 14:50

    Here is an example of how to use System.Linq.Expressions to add to Tim's answer. Obviously it isn't the prettiest code but having it in this nice tree-like form makes development so easy.

    private  Expression<IsWordChar> CreateIsWordCharExpression()
    {
        var e = Expression.Parameter(typeof(int), "e");
        var c = Expression.Variable(typeof(char), "c");
        var returnLabel = Expression.Label(Expression.Label(typeof(bool)), _falseConstant);
        var lambda = Expression.Lambda<IsWordChar>(
            Expression.Block(
                new[] { c },
                Expression.IfThen(
                    Expression.OrElse(
                        Expression.Equal(e, Expression.Constant(-1)),
                        Expression.Equal(e, _inputLengthVar)
                    ),
                    Expression.Return(returnLabel.Target, _falseConstant)
                ),
                Expression.Assign(c, Expression.MakeIndex(_str, _stringCharsPropertyInfo, new[] { e })),
                Expression.IfThenElse(
                    Expression.OrElse(
                        Expression.OrElse(
                            Expression.OrElse(
                                Expression.AndAlso(
                                    Expression.GreaterThanOrEqual(c, Expression.Constant('a')),
                                    Expression.LessThanOrEqual(c, Expression.Constant('z'))
                                ),
                                Expression.AndAlso(
                                    Expression.GreaterThanOrEqual(c, Expression.Constant('A')),
                                    Expression.LessThanOrEqual(c, Expression.Constant('Z'))
                                )
                            ),
                            Expression.AndAlso(
                                Expression.GreaterThanOrEqual(c, Expression.Constant('0')),
                                Expression.LessThanOrEqual(c, Expression.Constant('1'))
                            )
                        ),
                        Expression.Equal(c, Expression.Constant('_'))
                    ),
                    Expression.Return(returnLabel.Target, _trueConstant),
                    Expression.Return(returnLabel.Target, _falseConstant)
                ),
                returnLabel
            ),
            "IsWordChar",
            new[] { e }
        );
        return lambda;
    }
    
    0 讨论(0)
提交回复
热议问题