【问题标题】:Using Powershell to access Static class within a Static Class使用 Powershell 访问静态类中的静态类
【发布时间】:2013-09-24 08:11:12
【问题描述】:

我有一个像下面这样的类

namespace Foo.Bar
{
    public static class ParentClass
    {
      public const string myValue = "Can get this value";

      public static class ChildClass
      {
        public const string myChildValue = "I want to get this value";
      }
     }
}

我可以使用 powershell 获取 myValue,

[System.Reflection.Assembly]::LoadWithPartialName("Foo.Bar")
$parentValue = [Foo.Bar.ParentClass]::myValue

但我无法在 myChildValue 类中获取该类。有人可以帮忙吗?

认为它可能如下所示,但 $childValue 始终为空。

[System.Reflection.Assembly]::LoadWithPartialName("Foo.Bar")
$childValue = [Foo.Bar.ParentClass.ChildClass]::myChildValue

【问题讨论】:

    标签: class powershell static


    【解决方案1】:

    它是[Foo.Bar.ParentClass+ChildClass]。在 PowerShell 3 选项卡完成上会告诉你很多。此外,您还可以使用Add-Type 直接编译和加载代码:

    C:\Users\Joey> add-type 'namespace Foo.Bar
    >> {
    >>     public static class ParentClass
    >>     {
    >>       public const string myValue = "Can get this value";
    >>
    >>       public static class ChildClass
    >>       {
    >>         public const string myChildValue = "I want to get this value";
    >>       }
    >>      }
    >> }'
    >>
    C:\Users\Joey> [Foo.Bar.ParentClass+ChildClass]::myChildValue
    I want to get this value
    

    无需摆弄 C# 编译器和 [Assembly]::LoadWithPartialName

    【讨论】:

    • 谢谢你这么快的回答加分。那是什么 + 符号,所以如果子类下面有一个类,我会是 Foo.Bar.ParentClass+ChildClass+ChildOfChildClass
    • + 来自该类的内部名称。 C# 使用点 . 来分隔命名空间和嵌套类,但 .NET 本身没有。当您也使用反射来访问类型时,这一点变得很明显(并且还记录了there,大约在页面的一半处)。所以是的,嵌套的嵌套类也将使用+
    • 感谢您的链接和解释。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 2011-07-31
    • 1970-01-01
    相关资源
    最近更新 更多