2014-09-27 23 views
0

我在PowerShell 3.0和4.0上试过这个。我在课堂中使用结构时遇到问题。我可以直接从PowerShell使用结构中的属性,而不会出现问题。我也可以在PowerShell中直接在类中使用任何标准类型的属性。但是,当我将两者结合起来(尝试在类中使用自定义类型的属性)时,我不能。如何在PowerShell中的用户定义的类中使用用户定义的结构?

任何帮助将不胜感激!

这里有一个快速的示例代码复制我所看到的:

$MyTest = Add-Type @" 
namespace MyTest 
{ 
    public struct Struct1 
    { 
     public string Property; 
    } 

    public class Class1 
    { 
     public struct Struct2 
     { 
      public string Property; 
     } 

     public string MyString; 
     public Struct1 Struct1Property; 
     public Struct2 Struct2Property; 
    } 
} 
"@ -PassThru 

$struct1 = New-Object -TypeName MyTest.Struct1 
$class1 = New-Object -TypeName MyTest.Class1 
$struct1.Property = 'test' 
$struct1.Property # Outputs: test 
$class1.MyString = 'test' 
$class1.MyString # Outputs: test 
$class1.Struct1Property.Property = 'test' 
$class1.Struct1Property.Property # Outputs: <nothing> 
$class1.Struct2Property.Property = 'test' 
$class1.Struct2Property.Property # Outputs: <nothing> 

我期待这两个$ class1.Struct1Property.Property和$ class1.Struct2Property.Property应该输出“测试”。

如果我使用VS2013编译与Console应用程序相同的代码,它工作得很好。

控制台应用程序代码:

using System; 

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      MyTest.Struct1 struct1; 
      MyTest.Class1 class1 = new MyTest.Class1(); 

      struct1.Property = "test"; 
      Console.WriteLine("struct1.Property: {0}", struct1.Property); 

      class1.Struct1Property.Property = "test"; 
      Console.WriteLine("class1.Struct1Property.Property: {0}", class1.Struct1Property.Property); 

      class1.Struct2Property.Property = "test"; 
      Console.WriteLine("class1.Struct2Property.Property: {0}", class1.Struct2Property.Property); 
     } 
    } 
} 

namespace MyTest 
{ 
    public struct Struct1 
    { 
     public string Property; 
    } 

    public class Class1 
    { 
     public struct Struct2 
     { 
      public string Property; 
     } 

     public string MyString; 
     public Struct1 Struct1Property; 
     public Struct2 Struct2Property; 
    } 
} 

输出:

struct1.Property: test 
class1.Struct1Property.Property: test 
class1.Struct2Property.Property: test 
+0

这些领域没有的特性,这使得一个很大的不同。如果它们是属性,那么等效的C#代码甚至不会编译。 – 2014-09-28 00:13:34

+0

你是指我的“财产”一词吗?我从Get-Member cmdlet的MemberType输出中偷取它。即使这个词本身是任意的,但我对任何混淆道歉。你是对的,他们确实是领域。无论如何,似乎PowerShell并不像C#那样处理结构。 – Hossy 2014-09-28 17:56:43

回答

相关问题