【问题标题】:Custom type in Powershell with Generics Collection as a member以泛型集合为成员的 Powershell 中的自定义类型
【发布时间】:2012-03-13 09:50:37
【问题描述】:

我想在我的 powershell 脚本中声明以下类型:

Add-Type @'
  public class VirtualMachine {
    string Name;
    string HostName;
    HashSet<string> Dependencies = new HashSet<string>();
  }
'@

但是编译器抱怨找不到HashSet。

如果我注释掉 HashSet 行,则该类型可以正常工作。我想我必须告诉 powershell 加载 System.Core 程序集,但我想不通。

拜托,谁能告诉我我错过了什么?

提前致谢。

[编辑:] 在您的快速帮助下,我设法解决了我的问题。谢谢你的时间。

这是我的最终代码:

Add-Type -ReferencedAssemblies System.Core  @"
  using System.Collections.Generic;
  public class VirtualMachine {
    public string Name;
    public string HostName;
    public HashSet<string> Dependencies = new HashSet<string>();
  }
"@

【问题讨论】:

    标签: generics object powershell collections custom-type


    【解决方案1】:

    像这样:

    Add-Type -ReferencedAssemblies System.Core  @"
    using System.Collections.Generic;
     public class VirtualMachine {
    
        public string Name { get; set; }
        public string HostName{ get; set; }   
        public HashSet<string> Dependencies { get; set; }
    
      }
    "@ 
    

    您必须添加对System.Core 的程序集引用并在您的c# 代码中添加using System.Collections.Generic

    【讨论】:

      【解决方案2】:

      您可以通过 Referenced Assemblies 参数添加引用。

      Add-Type -ReferencedAssemblies System.Core
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多