使用New-Object -Property设置嵌套类的属性

时间:2011-09-06 21:53:39

标签: powershell powershell-v2.0

假设我在一个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 : 

无论如何设置SomeClass,包括一个New-Object语句中Numbers的属性?

2 个答案:

答案 0 :(得分:7)

你不能直接但你可以使用

内联构造内部类
New-Object SomeClass -Property @{
'Name' = "Justin Dearing";
'Numbers' = New-Object InnerClass -Property  @{
  'A' = 1;
  'B' = 2;
 }  
};

答案 1 :(得分:1)

你应该这样做我相信:

New-Object SomeClass -Property @{
     'Name' = "Justin Dearing";
     Numbers = New-Object InnerClass -Property  @{
                'A' = 1;
                'B' = 2;
            };
} ;