使用 New-Object -Property 设置嵌套类的属性
假设我在 powershell 脚本内用 C# 定义了以下类:
Add-Type -TypeDefinition @"
public class InnerClass {
int a, b;
public int A { get { return a; } set { a = value; } }
public int B { get { return b; } set { b = value; } }
}
public class SomeClass {
string name;
public string Name { get { return name; } set { name= value; } }
InnerClass numbers;
public InnerClass Numbers { get { return numbers; } set { numbers = value; } }
}
"@
我可以像这样实例化 InnerClass
的实例:
New-Object InnerClass -Property @{
'A' = 1;
'B' = 2;
}
但是,如果我想实例化 SomeClass
并设置属性对于 InnerClass
以类似的方式,它会失败。
New-Object SomeClass -Property @{
'Name' = "Justin Dearing";
Numbers = @{
'A' = 1;
'B' = 2;
};
} ;
New-Object : The value supplied is not valid, or the property is read-only. Cha
nge the value, and then try again.
At line:20 char:11
+ New-Object <<<< SomeClass -Property @{
+ CategoryInfo : InvalidData: (:) [New-Object], Exception
+ FullyQualifiedErrorId : InvalidValue,Microsoft.PowerShell.Commands.NewOb
jectCommand
Name : Justin Dearing
Numbers :
是否有办法在一个 New-Object 语句中设置 SomeClass
,包括 Numbers
的属性?
Lets say I define the following classes in C# inside a powershell script:
Add-Type -TypeDefinition @"
public class InnerClass {
int a, b;
public int A { get { return a; } set { a = value; } }
public int B { get { return b; } set { b = value; } }
}
public class SomeClass {
string name;
public string Name { get { return name; } set { name= value; } }
InnerClass numbers;
public InnerClass Numbers { get { return numbers; } set { numbers = value; } }
}
"@
I can instantiate an instance of InnerClass
like so:
New-Object InnerClass -Property @{
'A' = 1;
'B' = 2;
}
However, if I want to instantiate SomeClass
and set the properties for InnerClass
in a similar manner, it fails.
New-Object SomeClass -Property @{
'Name' = "Justin Dearing";
Numbers = @{
'A' = 1;
'B' = 2;
};
} ;
New-Object : The value supplied is not valid, or the property is read-only. Cha
nge the value, and then try again.
At line:20 char:11
+ New-Object <<<< SomeClass -Property @{
+ CategoryInfo : InvalidData: (:) [New-Object], Exception
+ FullyQualifiedErrorId : InvalidValue,Microsoft.PowerShell.Commands.NewOb
jectCommand
Name : Justin Dearing
Numbers :
Is there anyway to set SomeClass
, including the properties of Numbers
in one New-Object statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能直接但你可以内联构造内部类
You can't directly but you can have the innerclass constructed inline with
我相信你应该这样做:
You should be doing like this I believe: