[英]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.