簡體   English   中英

如何將包含字符串的 Yaml object 反序列化到列表中<string> ?</string>

[英]How can I deserialize a Yaml object containing strings into a List<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> ,它有一個名為“DLLs”的條目,其中包含一個List<Object> 該列表中的對象都是字符串。 你有 go:

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM