当我开始使用 PowerShell 并探索自定义类时,我不断遇到这个奇怪的异常,它一直存在,直到我做出任何改变。
> PS C:\Users\Purpl_000> C:\PS\Node\NodeTest.ps1 Cannot convert the
> "Node" value of type "Node" to type "Node". At
> C:\PS\Node\NodeTest.ps1:5 char:1
> + [Node]$node1 = New-Object Node -Property @{Next=$null; Value=3};
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> + CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException
> + FullyQualifiedErrorId : RuntimeException Exception setting "Next": "Cannot convert the "Node" value of type "Node" to type
> "Node"." At C:\PS\Node\NodeTest.ps1:9 char:1
> + $node2.Next = $node1;
> + ~~~~~~~~~~~~~~~~~~~~
> + CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
> + FullyQualifiedErrorId : ExceptionWhenSetting New-Object : The value supplied is not valid, or the property is read-only. Change the
> value, and then try again. At C:\PS\Node\NodeTest.ps1:13 char:16
> + [Node]$node3 = New-Object Node -Property @{Next=$node2; Value=9};
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> + CategoryInfo : InvalidData: (:) [New-Object], Exception
> + FullyQualifiedErrorId : SetValueException,Microsoft.PowerShell.Commands.NewObjectCommand
> Cannot find an overload for "new" and the argument count: "2". At
> C:\PS\Node\NodeTest.ps1:22 char:1
> + [Node]$node4 = [Node]::new($node3, 12);
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> + CategoryInfo : NotSpecified: (:) [], MethodException
> + FullyQualifiedErrorId : MethodCountCouldNotFindBest
这是 Node.ps1
class Node
{
[Node]$Next;
[int]$Value;
# .ctor
Node([Node]$next, [int]$value)
{
$this.Next = $next;
$this.Value = $value;
}
# default .ctor
Node() {}
static [int] Method1([Node]$n1)
{
return $n1.Value;
}
static [Node] Method2([Node]$n2)
{
$n2.Value = $n2.Value + 5;
return $n2.Value;
}
}
这是 NodeTest.ps1
. 'C:\PS\Node\Node.ps1';
[Node]$node1 = New-Object Node -Property @{Next=$null; Value=3};
[Node]$node2 = [Node]::new();
$node2.Next = $node1;
$node2.Value = 5;
[Node]$node3 = New-Object Node -Property @{Next=$node2; Value=9};
[Node]$node4 = [Node]::new($node3, 12);
我在 PowerShell ISE 中工作。Node.ps1已保存并成功运行。NodeTest.ps1也被保存,但有时会爆炸,直到我对文件进行任何看似无关的更改,保存,然后再次运行脚本。在这一点上,它再次正常工作。已解决问题的更改示例:(1)添加额外的空白行,(2)删除额外的空白行,(3)添加注释等。
我明白
New-Object : The value supplied is not valid, or the property is read-only. Change the value, and then try again.
通过我对使用不正确类型时会发生什么的测试,但不太确定为什么我会间歇性地看到这个。通过在预期节点的位置传递一个int来故意重现该错误的简单示例。:)
[Node]$node3 = New-Object Node -Property @{Next=5; Value=9};
以下确实让我感到困惑。在向NodeTest.ps1添加一个空行之后,一个节点怎么可能不是一个节点,然后又神奇地成为一个节点?
Exception setting "Next": "Cannot convert the "Node" value of type "Node" to type "Node"."
任何信息、解释或教育将不胜感激!
谢谢大家!迈克尔