0

我已经在 PowerShell 3.0 和 4.0 上试过了。我在使用类中的结构时遇到问题。我可以直接从 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 编译与控制台应用程序相同的代码,它就可以正常工作。

控制台应用程序代码:

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
4