我有
function Foo($a,$b) { $o = @{} $o.A = $a $o.B = $b $post = @{} $post.X="x" $post.entity =$o $newton::SerializeObject($post) }
然后做
foo "a" "b"
我明白了
Exception calling "SerializeObject" with "1" argument(s): "Self referencing loop detected for property 'Value' with type 'System.Management.Automation.PSParameterizedProperty'. Path 'entity.Members[0]'."
然而
function Foo2($o) { $post = @{} $post.X="x" $post.entity =$o $newton::SerializeObject($post) } foo2 @{a="a"; b="b"}
工作良好.也
function foo3($a,$b) { $o = @{} $o.A = $a $o.B = $b $newton::SerializeObject($o) } foo3 "a" "b"
工作,但
foo3 "a" 1
失败
后者可以通过这样做来工作
$o.B= [Int32]::Parse($b.Tostring())
这一切似乎都很奇怪
Windows 7上的powershell v2,json.net 4.4.5
自我引用循环问题完全是……分配事物的顺序.以下示例有效:
function Foo($a,$b) { $o = @{} $post = @{} $post.entity =$o $o.A = $a $o.B = $b $post.X="x" [Newtonsoft.Json.JsonConvert]::SerializeObject($post) } Foo "a" "b" {"entity":{"A":"a","B":"b"},"X":"x"}
如果你在传递它之前转换类型,那么它将保持你的foo3函数通用:
function foo3($a,$b) { $o = @{} $o.A = $a $o.B = $b [Newtonsoft.Json.JsonConvert]::SerializeObject($o) } $var2 = [Int32]::Parse((1).Tostring()) Foo3 "a" $var2 {"A":"a","B":1}