Created
July 14, 2016 09:22
-
-
Save hsinjungwu/55a0a686b0ea7eefd6e27490a22e9ddf to your computer and use it in GitHub Desktop.
計算機小程式
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.CodeDom; | |
using System.CodeDom.Compiler; | |
using Microsoft.CSharp; | |
namespace Calculator | |
{ | |
internal class Program | |
{ | |
private static void Main(string[] args) | |
{ | |
while (true) | |
{ | |
Console.WriteLine("請輸入你的算式,如要離開請按【Q】"); | |
string input = Console.ReadLine(); | |
if (input.Length == 0) continue; | |
if (input.ToUpper() == "Q") break; | |
input = input.Replace("--", "+").Replace("+-", "-").Replace("-+", "-"); | |
string errorMsg; | |
double d = ConstructCs(input, out errorMsg); | |
if (errorMsg.Length > 0) Console.WriteLine(errorMsg); | |
else Console.WriteLine(string.Format("答案 = {0}\n", d)); | |
} | |
} | |
private static double ConstructCs(string input, out string errorMsg) | |
{ | |
string code = string.Format( | |
@"using System; | |
namespace Frank | |
{{ | |
public class Calculator | |
{{ | |
public double CalcIt() | |
{{ | |
double d = {0}f; | |
return d; | |
}} | |
}} | |
}}", input); | |
CSharpCodeProvider comp = new CSharpCodeProvider(); | |
CompilerParameters cp = new CompilerParameters(); | |
cp.ReferencedAssemblies.Add("system.dll"); | |
cp.GenerateExecutable = false; | |
cp.GenerateInMemory = true; | |
CompilerResults cr = comp.CompileAssemblyFromSource(cp, code); | |
if (cr.Errors.HasErrors) | |
{ | |
errorMsg = "輸入格式格式有誤\n"; | |
return -1; | |
} | |
dynamic c = cr.CompiledAssembly.CreateInstance("Frank.Calculator"); | |
errorMsg = string.Empty; | |
return c.CalcIt(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment