不能在 CSharpCodeProvider 脚本中包含 Newtonsoft JSON



我正在尝试在动态编译的脚本中使用JSON。然而,当我包含库并添加JObject时,我会收到以下错误:;类型"System.Dynamic.IDynamicMetaObjectProvider"是在未被引用的程序集中定义的。必须添加对程序集"System.Core,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089"的引用">

我包括了MathNet。数字很好。

这是我的设置

  • 控制台应用程序.NET Framework 4(因此它与运行时匹配编译(
  • Nuget安装MathNet.Numberics
  • Nuget安装Newtonsoft
  • 将运行时编译指向带有dll的调试文件夹

测试代码

using System;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using Microsoft.CSharp;
using System.Reflection;
using System.CodeDom.Compiler;
namespace ConsoleApp1
{
public class RunScript0
{

public bool Compile()
{
//Add using statements here
string source = "namespace UserScriptrn{rnusing System;rn" +
"using System.IO;rn" +
"using System.Collections.Generic;rn" +
"using MathNet.Numerics.Distributions;rn" +
"using Newtonsoft.Json.Linq;rn" +
"using Newtonsoft.Json;rn" +
"public class RunScriptrn{rn" +
"private const int x = 99;rn" +
"public int Eval()rn{rn" +
//Remove following line and all works fine
"JObject j = new JObject();rn" +
"return x; rnrn}rn}rn}";
Dictionary<string, string> provOptions =
new Dictionary<string, string>();
provOptions.Add("CompilerVersion", "v4.0");
CodeDomProvider compiler = new CSharpCodeProvider(provOptions);

CompilerParameters parameters = new CompilerParameters();
string appPath = System.IO.Directory.GetCurrentDirectory();
parameters.ReferencedAssemblies.Add(appPath + "\MathNet.Numerics.dll");
parameters.ReferencedAssemblies.Add(appPath + "\Newtonsoft.Json.dll");
//Tried adding but didn't help parameters.ReferencedAssemblies.Add(appPath + "\System.Core.dll");
parameters.GenerateInMemory = true;
var results = compiler.CompileAssemblyFromSource(parameters, source);
// Check for compile errors / warnings
if (results.Errors.HasErrors || results.Errors.HasWarnings)
{
Console.WriteLine(results.Errors.Count.ToString() + " Erorrs");
for (int i = 0; i < results.Errors.Count; i++)
Console.WriteLine(results.Errors[i].ToString());
return false;
}
else
{
Console.WriteLine("Compiled Successfully");
return true;
}
}
}
class Program
{
static void Main(string[] args)
{
RunScript0 A = new RunScript0();
A.Compile();
}
}
}

您需要从GAC(全局程序集缓存(添加对SystemSystem.Core的引用:

parameters.ReferencedAssemblies.Add("System.dll");
parameters.ReferencedAssemblies.Add("System.Core.dll");

我认为这取决于Newtonsoft.Json.

相关内容

  • 没有找到相关文章

最新更新