如何将包含字符串的 Yaml 对象反序列化为列表<string>?



我创建了一个带有文件名的Yaml,因此我可以让我的程序检查列表中的每个文件是否存在。我还没有用 yaml 做太多事情,而且文档并没有真正帮助我。

这是我的Yaml(它很小):

DLLs:
- Filename1
- Filename2
- Filename3

目前,这是我的代码:

using (var reader = new StringReader(File.ReadAllText("./Libraries/DLLList.yml")))
{
/*
* List<string> allDllsList = deserialized yaml.getting all values of the "DLLs"-list
*/
var deserializer = new Deserializer();
var dlls = deserializer.Deserialize<dynamic>(reader)["DLLs"] as List<Object>;
/*This gives me the Error "Object System.Collections.Generic.Dictionary`2[System.Object,System.Object] cannot be converted into "System.String""*/
List<string> allDllsList = dlls.Cast<String>().ToList();
}

有人可以向我解释如何从 Yaml 文件中获取值,以及为什么它以您的方式工作?

编辑:现在它可以工作了,我使用了错误的yaml,我有2个版本

首先,从deserializer.Deserialize<dynamic>(reader)中获取返回值,并在调试器中检查它。这是一个Dictionary<String, Object>,它有一个名为"DLL"的条目,其中包含一个List<Object>。该列表中的对象都是字符串。给你:

var dlls = deserializer.Deserialize<dynamic>(reader)["DLLs"] as List<Object>;
//  Use .Cast<String>() as shown if you want to throw an exception when there's something 
//  that does not belong there. If you're serious about validation though, that's a bit 
//  rough and ready. 
//  Use .OfType<String>() instead if you want to be permissive about additional stuff 
//  under that key.
List<string> allDllsList = dlls.Cast<String>().ToList();

相关内容

最新更新