Фрагмент для ознакомления
Matches(eval); foreach (Match m in matches) { // if the word is found in the math member map, add a Math prefix to it bool isContainedInMathLibrary = _mathMembersMap[m.Value.ToUpper()] != null; if (replacelist.Contains(m.Value) == false && isContainedInMathLibrary) { eval = eval.Replace(m.Value, "Math." + _mathMembersMap[m.Value.ToUpper()]); } // we matched it already, so don't allow us to replace it againreplacelist.Add(m.Value); } Regex regularExpression2 = new Regex("[0-9]x"); // find all matches of type numx matches = regularExpression2.Matches(eval); string evalOld = eval; int count = 0; foreach (Match m in matches) { count++; // if the word is found in the math member map, add a Math prefix to it eval = eval.Substring(0, m.Index + count) + "*" + eval.Substring(m.Index + count); } Regex regularExpression3 = new Regex(@"x\^[0-9\.\-]+"); // find all matches of type numx matches = regularExpression3.Matches(eval); foreach (Match m in matches) { count++; // if the word is found in the math member map, add a Math prefix to it // eval = eval.Replace(m.Value, "Math.Pow(x," + m.Value.Substring(m.Value.IndexOf("^") + 1) + ")"); string replaceString = "x"; for (int i = 0; i < Convert.ToInt32(m.Value.Substring(m.Value.IndexOf("^") + 1)) - 1; i++) {replaceString = replaceString + "*x"; } eval = eval.Replace(m.Value, replaceString); } // return the modified evaluation string return eval; } /// /// Compiles the c# into an assembly if there are no syntax errors /// /// private CompilerResultsCompileAssembly() { // create a compilerICodeCompiler compiler = CreateCompiler(); // get all the compiler parametersCompilerParametersparms = CreateCompilerParameters(); // compile the code into an assemblyCompilerResults results = CompileCode(compiler, parms, _source.ToString()); return results; } void GetMathMemberNames() { // get a reflected assembly of the System assembly Assembly systemAssembly = Assembly.GetAssembly(typeof(System.Math)); try { //cant call the entry method if the assembly is null if (systemAssembly != null) { //Use reflection to get a reference to the Math class Module[] modules = systemAssembly.GetModules(false); Type[] types = modules[0].GetTypes(); //loop through each class that was defined and look for the first occurrance of the Math class foreach (Type type in types) { if (type.Name == "Math") { // get all of the members of the math class and map them to the same member // name in uppercaseMemberInfo[] mis = type.GetMembers(); foreach (MemberInfo mi in mis) { _mathMembers.Add(mi.Name); _mathMembersMap[mi.Name.ToUpper()] = mi.Name; } } } } } catch (Exception ex) {Console.WriteLine("Error: An exception occurred while executing the script", ex); } } private float _result = 0.0f; public float Result { get { return _result; } } /// /// Runs the Calculate method in our on-the-fly assembly /// /// public Complex RunCode(Complex testVal) { Assembly executingAssembly = _results.CompiledAssembly; try { //cant call the entry method if the assembly is null if (executingAssembly != null) { object assemblyInstance = executingAssembly.CreateInstance("ExpressionEvaluator.Calculator"); //Use reflection to call the static Main function Module[] modules = executingAssembly.GetModules(false); Type[] types = modules[0].GetTypes(); //loop through each class that was defined and look for the first occurrance of the entry point method foreach (Type type in types) {MethodInfo[] mis = type.GetMethods(); foreach (MethodInfo mi in mis) { if (mi.Name == "Calculate") { double[] result = (double[])mi.Invoke(assemblyInstance, new object[] { testVal.real, testVal.imag }); return new Complex(result[0], result[1]); } } } } } catch (Exception ex) {Console.WriteLine("Error: An exception occurred while executing the script", ex); } return new Complex(0, 0); }CodeMemberFieldFieldVariable(string fieldName, string typeName, MemberAttributesaccessLevel) {CodeMemberField field = new CodeMemberField(typeName, fieldName);field.Attributes = accessLevel; return field; }CodeMemberFieldFieldVariable(string fieldName, Type type, MemberAttributesaccessLevel) {CodeMemberField field = new CodeMemberField(type, fieldName);field.Attributes = accessLevel; return field; } /// /// Very simplistic getter/setter properties /// /// /// /// /// CodeMemberPropertyMakeProperty(string propertyName, string internalName, Type type) {CodeMemberPropertymyProperty = new CodeMemberProperty();myProperty.Name = propertyName;myProperty.Comments.Add(new CodeCommentStatement(String.Format("The {0} property is the returned result", propertyName)));myProperty.Attributes = MemberAttributes.Public;myProperty.Type = new CodeTypeReference(type);myProperty.HasGet = true;myProperty.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), internalName)));myProperty.HasSet = true;myProperty.SetStatements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), internalName), new CodePropertySetValueReferenceExpression())); return myProperty; } /// /// Main driving routine for building a class /// void BuildClass(string expression) { // need a string to put the code into _source = new StringBuilder();StringWritersw = new StringWriter(_source); //Declare your provider and generatorCSharpCodeProvidercodeProvider = new CSharpCodeProvider();ICodeGenerator generator = codeProvider.CreateGenerator(sw);CodeGeneratorOptionscodeOpts = new CodeGeneratorOptions();CodeNamespacemyNamespace = new CodeNamespace("ExpressionEvaluator");myNamespace.Imports.Add(new CodeNamespaceImport("System"));myNamespace.Imports.Add(new CodeNamespaceImport("System.Windows.Forms")); //Build the class declaration and member variablesCodeTypeDeclarationclassDeclaration = new CodeTypeDeclaration();classDeclaration.IsClass = true;classDeclaration.Name = "Calculator";classDeclaration.Attributes = MemberAttributes.Public;classDeclaration.Members.Add(FieldVariable("answer", typeof(Complex), MemberAttributes.Private)); //default constructorCodeConstructordefaultConstructor = new CodeConstructor();defaultConstructor.Attributes = MemberAttributes.Public;defaultConstructor.Comments.Add(new CodeCommentStatement("Default Constructor for class", true));defaultConstructor.Statements.Add(new CodeSnippetStatement("//TODO: implement default constructor"));classDeclaration.Members.Add(defaultConstructor); //propertyclassDeclaration.Members.Add(this.MakeProperty("Answer", "answer", typeof(Complex))); //Our Calculate MethodCodeMemberMethodmyMethod = new CodeMemberMethod();myMethod.Name = "Calculate";myMethod.Parameters.Add(new CodeParameterDeclarationExpression("System.Double", "real"));myMethod.Parameters.Add(new CodeParameterDeclarationExpression("System.Double", "imag"));myMethod.ReturnType = new CodeTypeReference(typeof(double[]));myMethod.Comments.Add(new CodeCommentStatement("Calculate an expression", true));myMethod.Attributes = MemberAttributes.Public;myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("Complex x"), new CodeSnippetExpression("new Complex(real,imag)")));myMethod.Statements.Add(new CodeAssignStatement(new CodeSnippetExpression("Answer"), new CodeSnippetExpression(expression))); // myMethod.Statements.Add(new CodeSnippetExpression("MessageBox.Show(String.Format(\"Answer = {0}\", Answer))"));myMethod.Statements.Add( new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "Answer.ToDoubleArray()")));classDeclaration.Members.Add(myMethod); //write codemyNamespace.Types.Add(classDeclaration);generator.GenerateCodeFromNamespace(myNamespace, sw, codeOpts);sw.Write(@" /// /// /// public class Complex { public double real = 0.0; public double imag = 0.0; public Complex(double rval, double ival) { // // TODO: Add Constructor Logic here //real = rval;imag = ival; } public static Complex operator +(Complex val1, Complex val2) { return (new Complex(val1.real + val2.real, val1.imag + val2.imag)); } public static Complex operator -(Complex val1, Complex val2) { return (new Complex(val1.real - val2.real, val1.imag - val2.imag)); } public float[] ToFloatArray() { float[] result = new float[2]; result[0] = (float)real; result[1] = (float)imag; return result; } public double[] ToDoubleArray() { double[] result = new double[2]; result[0] = real; result[1] = imag; return result; } public static Complex operator *(Complex val1, Complex val2) { return (new Complex(val1.real * val2.real - val1.imag * val2.imag, val1.real * val2.imag + val2.real * val1.imag)); } public static Complex operator *(double val1, Complex val2) { return (new Complex( ((double)val1) * val2.real, ((double)val1) * val2.imag)); } public static Complex operator *(Complex val2, double val1) { return (new Complex((double)val1 * val2.real, (double)val1 * val2.imag)); } public static Complex operator +(double val1, Complex val2) { return (new Complex((double)val1 + val2.real, val2.imag)); } public static Complex operator +(Complex val2, double val1) { return (new Complex((double)val1 + val2.real, val2.imag)); } public static Complex operator -(double val1, Complex val2) { return (new Complex((double)val1 - val2.real, val2.imag)); } public static Complex operator -(Complex val2, double val1) { return (new Complex((double)val2.real - val1, val2.imag)); } public Complex Scale(double val) { real *= val;imag *= val; return this;} }");sw.Flush();sw.Close(); } }}
1. Goldberg D. E. Genetic Algorithms in Search, Optimization, and Machine Learning. Addison Wesley Publishing Company, 1989
2. Емельянов В. В., Курейчик В. В., Курейчик В. М. Теория и практика эволюционного моделирования, 2003
3. D.Rivero, M.Gestal, J.R.Rabunal. Genetic Programming. Key Concepts and Examples. A Biref Tutorial on Genetic Programming. Lambert Academic Publishing, 2011. ISBN 9783845438450.
4. https://mywebcenter.ru/osnovy-kompilyacii-i-vypolneniya-koda-na-letu-v-c-4356/
5. Троелсен, Эндрю Язык программирования C# 5.0 и платформа .NET 4.5 / Эндрю Троелсен. - М.: Вильямс, 2015. - 486 c.
6. Рихтер Дж. "CLR via C#. Программирование на платформе Microsoft.NET Framework 4.5 на языке C#" – М.: Питер, 2023. – 896с