首先,感谢阅读。此外,我需要你的帮助!
顺便说一下,我正在使用Newtonsoft.Json;
如何为此添加字符串:
obj.namedTypes.Menu.fields&LT。字符串> = new ExpandoObject();
所以我现在有这个代码:
internal class Program
{
private static void Main(string[] args)
{
Regex reg = new Regex(":addSubMenu\\((?<Description>.+),[a-z A-Z](\'|\")(?<Identifier>[a-zA-Z]+)(\'|\")\\)"); //Regular expression for finding the id and description i want.
dynamic obj = new ExpandoObject();
obj.global = new ExpandoObject();
obj.global.type = "table";
obj.global.fields = new ExpandoObject();
obj.global.fields.scriptConfig = new ExpandoObject();
obj.global.fields.scriptConfig.type = "function";
obj.global.fields.scriptConfig.args = new string[] {};
obj.global.fields.scriptConfig.description = "a simple description";
obj.global.fields.scriptConfig.returnTypes = new List<ExpandoObject>();
dynamic arguments = new ExpandoObject();
arguments.type = "ref";
arguments.name = "Menu";
obj.global.fields.scriptConfig.returnTypes.Add(arguments);
obj.namedTypes = new ExpandoObject();
obj.namedTypes.Menu = new ExpandoObject();
obj.namedTypes.Menu.type = "table";
obj.namedTypes.Menu.fields = new ExpandoObject();
Console.WriteLine(JsonConvert.SerializeObject(obj, Formatting.Indented));
MatchCollection matches = reg.Matches(File.ReadAllText("test.txt"));
string description;
string value;
foreach (Match m in matches)
{
description = m.Groups["Description"].ToString();
value = m.Groups["Identifier"].ToString();
/* I want to add the value as a object like this: ->
* obj.namedTypes.Menu.fields.<value> = new ExpandoObject();
* obj.namedTypes.Menu.fields.<value>.description = description;
*/
Console.WriteLine($"Description: {description}\nValue: {value}");
}
Console.ReadLine();
}
我想将值添加为如下对象: - &gt;
obj.namedTypes.Menu.fields.<value> = new ExpandoObject();
obj.namedTypes.Menu.fields.<value>.description = description;
答案 0 :(得分:1)
尝试使用词典。
您修改的代码将是 -
//Initialization of Dictonary
obj.namedTypes.Menu.fields = new Dictionary<string,string>();
//Reading from File and iteration on matches
MatchCollection matches = reg.Matches(File.ReadAllText("test.txt"));
string description;
string value;
foreach (Match m in matches)
{
description = m.Groups["Description"].ToString();
value = m.Groups["Identifier"].ToString();
obj.namedTypes.Menu.fields.Add(description , value);
}
//End: Serialize the Whole stuff
Console.WriteLine(JsonConvert.SerializeObject(obj, Formatting.Indented));