這是一個簡化且完整的代碼示例:
class DediInfo {
[string]$ServiceName
[int]$QueryPort
DediInfo([string]$servicename, [int]$qPort){
$this.ServiceName = $servicename
$this.QueryPort = $qPort
}
}
class DediInfos {
hidden static [DediInfos] $_instance = [DediInfos]::new()
static [DediInfos] $Instance = [DediInfos]::GetInstance()
[System.Collections.Generic.List[DediInfo]]$Dedis = [System.Collections.Generic.List[DediInfo]]::New()
hidden static [DediInfos] GetInstance() {
return [DediInfos]::_instance
}
[void]SaveInfo(){
$this.Dedis | Export-Clixml "D:\test.xml"
}
[void]LoadInfo() {
$this.Dedis = Import-Clixml "D:\test.xml"
}
}
$dInfos = [DediInfos]::Instance
$dInfos.Dedis.Add([DediInfo]::New("service1", 15800))
$dInfos.Dedis.Add([DediInfo]::New("service2", 15801))
$dInfos.SaveInfo()
$dInfos.Dedis = [System.Collections.Generic.List[DediInfo]]::New()
$dInfos.LoadInfo()
這是我收到的例外:
Exception setting "Dedis": "Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Collections.Generic.List`1[DediInfo]"."
At D:\test.ps1:25 char:9
$this.Dedis = Import-Clixml "D:\test.xml"
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
FullyQualifiedErrorId : ExceptionWhenSetting
在過去的 4 個小時里,我嘗試了不同的排列:
- 添加
[Serializable()]到第一類 - 使用
ConvertTo-Xml在List<>保存之前從檔案中讀取后 - 打破加載步驟以首先轉儲到一個新串列中 - 它確實從檔案中加載資料,但我不能把它放回單例的 List<> 因為它加載為
System.Object - 嘗試使用保存到 json(如下)和相同的錯誤訊息
-
$this.Dedis | ConvertTo-Json | Set-Content "D:\test.json"
-
$this.Dedis = Get-Content -Raw "D:\test.json" | ConvertFrom-Json
- 許多其他的嘗試,我不再記得了。
我想要的只是一種將List<>檔案保存到檔案然后在我的下一個腳本運行時再次加載它的方法。這個例子非常簡化;它保存,清除,然后嘗試再次加載以顯示我正在處理的內容。我讀過的所有地方都是 Import-Clixml 應該將 XML 檔案作為原始物件加載回,但我沒有任何運氣。
uj5u.com熱心網友回復:
Import-XML確實加載回物件,但不太尊重型別。在匯出之前,您有一個 DediInfo 物件串列。匯入后,您現在擁有一組Deserialized.DediInfo物件。
您可以通過執行匯入并檢查第一個 dediinfo 物件的基本型別來看到這一點。
$Imported = Import-Clixml "D:\test.xml"
$Imported[0].psobject.TypeNames
它會顯示
Deserialized.DediInfo
Deserialized.System.Object
因此,您的轉換失敗,因為您試圖將其轉換回其原始型別,這是不可能的。
匯入 XML 后,您必須再次構建 DediInfo 串列。這是對您的簡單修改LoadInfo,將起作用。
[void]LoadInfo() {
$this.Dedis = Foreach ($i in Import-Clixml "D:\test.xml") {
[DediInfo]::New($i.ServiceName, $i.QueryPort)
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/358650.html
