【发布时间】:2019-10-24 18:45:35
【问题描述】:
我创建了一个如下所示的 Yaml:
Directories:
- ./Libraries:
- DLLList.yml
- ./Output:
- None
现在我将该 yaml 反序列化为对象列表:
List<object> allDirectoriesList = new List<object>();
List<string> allFileNames = new List<string>();
using (var reader = new StringReader(File.ReadAllText("./FileConfig.yml")))
{
allDirectoriesList = deserializer.Deserialize<dynamic>(reader)["Directories"] as List<Object>;
}
foreach (var directory in allDirectoriesList)
{
var directoryAsDictionary = (Dictionary<object, object>)directory;
List<object> list = directoryAsDictionary.Select(kvp => kvp.Value).ToList();
IEnumerable<string> _fileList = list.Select(i => i.ToString());
List<string> fileList = _fileList.ToList<string>();
for (int i = 0; i < fileList.Count(); i++)
{
var x = (string)list[i];
}
}
directory 是 Dictionary 类型的对象,我在这部分将其转换为 List:
var directoryAsDictionary = (Dictionary<object, object>)directory;
List<object> list = directoryAsDictionary.Select(kvp => kvp.Value).ToList();
此list 包含 1 个字符串类型的对象,其中存储了文件名。但我无法将这些字符串从对象中取出。如果我转换它们,或者将它们转换为 ToString(),我总是得到 "System.Collections.Generic.List`1[System.Object]",但在这种情况下它必须是 "DLLList.yml"
【问题讨论】:
-
@jdweng YAML 不是二进制数据。它只是另一种文本格式。像 JSON
-
当我阅读您的代码时,我认为您正在构建一个对象列表,这些对象实际上是具有对象类型键的对象字典。这将涉及大量转换以获取字典中的字符串。为什么您构建的数据结构如此复杂?既然知道要存储字典,为什么还需要对象类型?你真的需要创建未知类型和未知键类型的字典吗??