d--*_*--b 5 c# powershell interpreter
我正在考虑为 C# 创建一个可以加载到某些应用程序中的小型解释器。可以运行这样的东西:
> var arr = new[] { 1.5,2.0 };
arr = { 1.5, 2.0 }
> var sum = arr.Sum();
sum = 3.5
Run Code Online (Sandbox Code Playgroud)
所以我认为这可以通过创建一个包含所有变量及其类型的字典来实现,然后编译每一行,然后执行函数,获取结果并将其粘贴到变量字典中。
但是,在我看来,这实际上可能很难构建并且可能非常低效。
然后我认为 Powershell 正在做我需要的事情。但它是如何完成的?任何人都可以启发我了解 Powershell 的工作原理,或者构建 .Net 解释器的好方法是什么?
您如何在您的应用程序中托管 PowerShell 引擎并让它为您进行解释?例如:
private static void Main(string[] args)
{
// Call the PowerShell.Create() method to create an
// empty pipeline.
PowerShell ps = PowerShell.Create();
// Call the PowerShell.AddScript(string) method to add
// some PowerShell script to execute.
ps.AddScript("$arr = 1.5,2.0"); # Execute each line read from prompt
// Call the PowerShell.Invoke() method to run the
// commands of the pipeline.
foreach (PSObject result in ps.Invoke())
{
Console.WriteLine(result.ToString());
}
}
Run Code Online (Sandbox Code Playgroud)
如果您的目标是学习如何构建解释器,请查看解释器模式。
| 归档时间: |
|
| 查看次数: |
1482 次 |
| 最近记录: |