我正在尝试执行字符串变量中的代码以从字典中获取项目
我尝试过像这样使用CSharpCodeProvider:
var text = "IconDescription";
text = "\"" + text + "\"";
var field = "Outcome[" + text + "].Value";
field = "\"" + field + "\"";
CSharpCodeProvider codeProvider = new CSharpCodeProvider();
ICodeCompiler icc = codeProvider.CreateCompiler()
parameters.GenerateExecutable = true;
CompilerResults results = icc.CompileAssemblyFromSource(parameters, field)
var dataTest = JsonConvert.DeserializeObject<DictionaryOutcome.Rootobject>(jsonText);
var t = new List<Outcome>();
var defaultOutcome = dataTest.Response.Outcome.KeyValueOfstringOutcomepQnxSKQu.Select(item => new Outcome
{
DataType = item.Value.DataType,
Value = item.Value.Value1,
Field = item.Key
}).ToList();
defaultOutcome.ToList().ForEach(item =>
{
t.Add(item);
});
字段变量的值是Outcome [“IconDescription”]。值,我想执行此代码以使用“IconDescription”键从Outcome字典中获取值,并获取值。
这可能吗?
我尝试过以下方法:
var scriptOptions = ScriptOptions.Default
.WithReferences(typeof(Dictionary<string, Outcome>).FullName)
.WithImports("Outcome");
var scripts = CSharpScript.Create<object>(field, scriptOptions);
var resultsx = scripts.RunAsync(null, CancellationToken.None).Result;
我收到这个错误:
错误CS0246:找不到类型或命名空间名称'Outcome'(您是否缺少using指令或程序集引用?)
我正在努力甚至猜测你想要做什么,但作为一个初学者,通过尝试编译你正在构建的字符串来考虑你实际在做什么。
Outcome["SomeValue"].Value
甚至不是有效的C#代码:
Outcome
未定义你正在将它编译成一个可执行文件,所以我看不出它如何知道从反序列化JSON内容带来的结果列表,你没有指明从哪里得到它。
您没有指定任何证据来解释为什么您需要这样一个精心设计的解决方案来仅从JSON中提取一些值,因此一个简单的解决方案可能是使用Newtonsoft.Json的内置功能:
当json对象是数组时,dataTest[0]
选择数组中的第一个元素;
dataTest[0]["Outcome"]
选择第一个对象的属性Outcome
,它本身可能是一个对象
dataTest[0]["Outcome"]["Value"]
选择了Value
的物业Outcome
这里的所有字符串索引只能在运行时知道并保存在变量中。我不明白为什么你需要做任何脚本来做这件事。