Преобразование строки в код - C# (180100)
Формулировка задачи:
Всем привет, у меня такой вопрос:
Возможно ли преобразовать строку (например из "textBox1.Text") в код?
Решение задачи: «Преобразование строки в код»
textual
Листинг программы
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.CSharp;
namespace MathEvalNS
{
class Program
{
static void Main(string[] args)
{
string input = "Math.Cos(5) * 180 / Math.PI";
var func = MathEvaluator.Parse(input);
Console.WriteLine(func(5));
}
}
public static class MathEvaluator
{
public static Func<double, double> Parse(string input)
{
var provider = new CSharpCodeProvider();
var parameters = new CompilerParameters { GenerateInMemory = true };
parameters.ReferencedAssemblies.Add("System.dll");
try
{
var results = provider.CompileAssemblyFromSource(parameters, $@"
using System;
public static class LambdaCreator
{{
public static double F(double x)
{{
return {input};
}}
}}");
var method = results.CompiledAssembly.GetType("LambdaCreator").GetMethod("F");
return (Func<double, double>) Delegate.CreateDelegate(typeof(Func<double, double>), null, method);
}
catch (FileNotFoundException)
{
throw new ArgumentException("Input should be valid C# expression", nameof(input));
}
}
}
}