Ric*_*rth 8 class introspection raku
我有一个带有属性的类。我想检查是否定义了一些但不是全部。所以:
class A {
has $.a is rw;
has $.b is rw;
has $.c is rw;
has $.d is rw;
method delete { ... }
}
my A $x .= new(:a<hi>, :d<good>);
## later
$x.b = 'there';
## code in which $x.c may or may not be defined.
## now I want to check if the attributes a, b, and c are defined, without
## needing to know about d
my Bool $taint = False;
for <a b c> {
$taint &&= $x.$_.defined
}
Run Code Online (Sandbox Code Playgroud)
这将导致错误,因为类型 A 的对象没有用于类型字符串的方法“CALL-ME”。
是否有一种内省方法可以为我提供类的属性值?
$x.^attributes 给我他们的名字和类型,但不是他们的价值。
我认为必须有某种方式自dd或.perl提供属性值 - 我认为。
是的,它被称为get_value。它需要传递给它的属性的对象。例如:
class A {
has $.a = 42;
has $.b = 666;
}
my $a = A.new;
for $a.^attributes -> $attr {
say "$attr.name(): $attr.get_value($a)"
}
# $!a: 42
# $!b: 666
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |