簡體   English   中英

如何在PowerShell中的用戶定義類中使用用戶定義的結構?

[英]How Do I Use a User-Defined Struct in a User-Defined Class in PowerShell?

我已經在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都應輸出“ test”。

如果我使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM