generics - Powershell 中的自定义类型,将泛型集合作为成员

标签 generics object powershell collections custom-type

我想在我的 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>();
  }
"@

最佳答案

像这样:

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

关于generics - Powershell 中的自定义类型,将泛型集合作为成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9681711/

相关文章:

c# - VS Designer 错误 : GenericArguments[0], 'X' on 'Y' 违反了类型参数 'Z' 的约束

python - 如何在python中保存和恢复多个变量?

windows - 使用 powershell 删除文件中的特定行

java - 我们可以在将字符串加载到 Arraylist 对象时限制特定的字符串大小写吗?

generics - f# 泛型类型比较

javascript - 操纵对象结构

sql-server - 尽管安装了 SQL Server,但未安装 SQL Server PowerShell 管理单元

powershell - Sync-WDSite Web 应用程序物理路径参数

Java 泛型,无法从 E 转换为 E

object - D 中的自动数据持久化