是否有正确/最好/任何方法使用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类中使构造函数(或任何其他方法)成为私有的吗?
答案 0 :(得分:3)
您的方法是可见的,因为它不是静态的:
[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()
答案 1 :(得分:1)
这个怎么样?
class ScannerGeometry
{
[int] $EEprom; # read eeprom
# ....
ScannerGeometry()
{
# ... fetch calibration from instrument
}
[ScannerGeometry] Instance() {
if ($this -eq $null)
{
$this = [ScannerGeometry]::new()
}
return $this
}
}
$scangeo = [ScannerGeometry]::new().Instance()
PS:代码只是没有错误,我对单例上下文完全无能为力:(