我想创建一个方法作为给定</ p>的数学表达式求值器
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using System;
using System.Numerics;
using System.Text.RegularExpressions;
public class Dummy
{
public Complex x;
public Complex y;
}
namespace Simpler
{
static class Program
{
public static Complex Function(this string e, Complex x, Complex y)
{
Script<Complex> s = CSharpScript.Create<Complex>(e, globalsType: typeof(Dummy));
Complex z = s.RunAsync(new Dummy { x = x, y = y }).Result.ReturnValue;
return z;
}
static void Main(string[] args)
{
Complex x = new Complex(1, 1); // x = 1 + i
Complex y = new Complex(0, 1); // y = i
//string e = "x*y"; // x*y = (1 + i)* i = i + i^2 = i - 1 = -1 + i
string e = "x/y"; // x/y = (1 + i)/ i = 1/i + 1 = -i + 1 = 1 - i
string lhs = Regex.Replace(e, "x", x.ToString());
lhs = Regex.Replace(lhs, "y", y.ToString());
Console.WriteLine($"{lhs} = {e.Function(x, y)}");
}
}
}
我们可以将Dummy
从全局命名空间移动到我自己的命名空间Simpler
吗?
答案 0 :(得分:1)
只需将类复制到您的名称空间中,如下所示:
namespace Simpler
{
public class Dummy
{
public Complex x;
public Complex y;
}
}
我建议将它放在另一个名为Dummy.cs的文件或类似的文件中。完成后,您应该可以从Namespace Simpler访问此类。