如何从 PowerShell 中的静态方法动态引用类和静态属性?

问题描述 投票:0回答:1

我有一个名为 DatabaseObject 的超类。此类实现了 Active Record 设计模式,将被所有其他访问数据库的继承。

PHP中,我可以这样写:

class DatabaseObject {
    protected static $database;
    ...

    public static function set_database($database) {
        self::$database = $database;
    }

    public static function find_all() {
        $sql = "SELECT * FROM " . static::$table_name;
        return static::find_by_sql($sql);
    }

    protected static function instantiate($record) {
        $object = new static;
        foreach($record as $property => $value) {
            if( property_exists($object, $property) ) {
                $object->$property = $value;
            }
        }
        return $object;
    }
    ...
}

注意使用关键字self::

static::
引用类的
dynamic
方式。在那种语言中,我们甚至可以做这样的事情:

$object = new static;

Python中,我们可以像这样创建一个类的实例:

@classmethod
def _instantiate(cls, record):
    # Creates an instance of the subclass.
    obj = cls

TypeScript中,我们可以做类似的事情:

protected static instantiate(record: object): object {
    const obj = new this();
    ...
    return obj;
}

如何在 PowerShell 中获得相同的结果?

目前我只能这样做:

static [void]SetDatabase($Database) {
        [DatabaseObject]::Database = $Database
}

我必须显式地写类名。 如果类应该被继承,它是行不通的。

你能告诉我正确的做法吗?

谢谢。

powershell class inheritance static-methods
1个回答
0
投票

PowerShell 中

self
的等价物是
$this
但只能用于实例方法而不是静态方法。基本上,如果您想 动态 反映来自静态方法的类型成员,您能做的最好的事情就是将类型本身作为参数传递。此外,没有看到从静态类继承的意义,但您可能有充分的理由。有关详细信息,请参阅关于课程

class Test {
    static [string] $Prop

    # with an instance method, can use `$this`
    [void] SetProp([string] $Value) {
        $this::Prop = $value
    }

    # with a static method, need to pass the target type
    static [void] SetProp([type] $TargetType, [string] $Value) {
        $TargetType::Prop = $Value
    }
}

[Test]::new().SetProp('foo')
[Test]::Prop # foo
[Test]::SetProp([Test], 'bar')
[Test]::Prop # bar
© www.soinside.com 2019 - 2024. All rights reserved.