我想在我的 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/