内容检查部分(不是全部)类属性 [英] Content checking some, not all, class attributes

查看:63
本文介绍了内容检查部分(不是全部)类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有属性的类.我想检查是否定义了一些但不是全部.所以:

I have a class with attributes. I want to check whether some but not all are defined. So:

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
}

这将导致错误,因为类型A的对象没有用于字符串类型的方法"CALL-ME".

This will cause errors because an object of type A doesn't have a method 'CALL-ME' for type string.

是否有一种自省方法可以为我提供类的属性值?

Is there an introspection method that gives me the values of attributes of a class?

$ x.^属性给出了它们的名称和类型,但没有给出它们的值.

$x.^attributes gives me their names and types, but not their values.

我认为必须采取某种方法,因为 dd .perl 提供属性值-我认为.

I think there must be some way since dd or .perl provide attribute values - I think.

推荐答案

是的,它称为 get_value .它需要传递给它的属性的对象.例如:

Yes, it is called get_value. It needs the object of the attribute passed to it. For example:

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

这篇关于内容检查部分(不是全部)类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆