是否有使用 PowerShell 5.0 中的类构造创建单例类的正确/最佳/任何方法?我试过这样的事情:
class ScannerGeometry
{
[int] $EEprom; # read eeprom
# ....
ScannerGeometry()
{
# ... fetch calibration from instrument
}
[ScannerGeometry] Instance() {
if ($this -eq $null)
{
$this = [ScannerGeometry]::new()
}
return $this
}
}
并将其分配给以下内容:
$scanner = [ScannerGeometry]::Instance()
唉,我收到运行时错误
Method invocation failed because [ScannerGeometry] does not contain a method named 'Instance'.
另外,可以在 PS5 类中将构造函数(或任何其他方法)设为私有(private)吗?
最佳答案
您的方法是这样可见的,因为它不是静态的:
[ScannerGeometry]::new() | set x
PS C:\Work> $x | gm
TypeName: ScannerGeometry
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
Instance Method ScannerGeometry Instance()
ToString Method string ToString()
EEprom Property int EEprom {get;set;}
您需要使用关键字
static
.在那种情况下 $this
无效,因此您必须稍微更改代码。这是代码:class ScannerGeometry
{
[int] $EEprom; # read eeprom
static [ScannerGeometry] Instance() {
return [ScannerGeometry]::new()
}
}
编辑
好的,这是工作代码:
class ScannerGeometry
{
[int] $EEprom # read eeprom
static [ScannerGeometry] $instance
static [ScannerGeometry] GetInstance() {
if ([ScannerGeometry]::instance -eq $null) { [ScannerGeometry]::instance = [ScannerGeometry]::new() }
return [ScannerGeometry]::instance
}
}
$s = [ScannerGeometry]::GetInstance()
关于Powershell 5 类和单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36751113/