【发布时间】:2021-12-25 20:04:12
【问题描述】:
这是一个简化且完整的代码示例:
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()] - 在保存之前和从文件读取之后在
List<>上使用ConvertTo-Xml - 首先打破加载步骤转储到一个新列表中 - 它确实从文件加载数据,但我不能将它放回单例列表,因为它加载为
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 文件作为原始对象加载回,但我没有任何运气。
【问题讨论】: