如何在 Perl6 中编写自定义访问器方法? [英] How does one write custom accessor methods in Perl6?

查看:46
本文介绍了如何在 Perl6 中编写自定义访问器方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Perl6 中编写自定义访问器方法?

How does one write custom accessor methods in Perl6?

如果我有这门课:

class Wizard {
    has Int $.mana is rw;
}

我可以这样做:

my Wizard $gandalf .= new;
$gandalf.mana = 150;

假设我想在不放弃 $gandalf.mana = 150; 符号的情况下向 Perl6 类中的 setter 添加一点检查(换句话说,我不想写这个:$gandalf.setMana(150);).如果程序试图设置负法力,它应该死掉.我该怎么做呢?Perl6 文档只是提到可以编写自定义访问器,但没有说明如何编写.

Let's say I want to add a little check to a setter in my Perl6 class without giving up the $gandalf.mana = 150; notation (in other words, I don't want to write this: $gandalf.setMana(150);). The program should die, if it tries to set a negative mana. How do I do this? The Perl6 documentation just mentions it is possible to write custom accessors, but does not say how.

推荐答案

您可以通过声明一个方法 is rw 来获得与 $.mana 提供的相同的访问器接口.然后你可以像这样在底层属性周围包裹一个代理:

You can get the same accessor interface that saying $.mana provides by declaring a method is rw. Then you can wrap a proxy around the underlying attribute like so:

#!/usr/bin/env perl6
use v6;

use Test;
plan 2;

class Wizard {
    has Int $!mana;

    method mana() is rw {
        return Proxy.new:
            FETCH => sub ($) { return $!mana },
            STORE => sub ($, $mana) {
                die "It's over 9000!" if ($mana // 0) > 9000;
                $!mana = $mana;
            }
    }
}

my Wizard $gandalf .= new;
$gandalf.mana = 150;
ok $gandalf.mana == 150, 'Updating mana works';
throws_like sub {
    $gandalf.mana = 9001;
}, X::AdHoc, 'Too much mana is too much';

Proxy 基本上是一种拦截对存储的读取和写入调用并执行除默认行为之外的其他操作的方法.正如它们的大写所暗示的那样,FETCHSTORE 被 Perl 自动调用来解析像 $gandalf.mana = $gandalf.mana + 5 这样的表达式.

Proxy is basically a way to intercept read and write calls to storage and do something other than the default behavior. As their capitalization suggests, FETCH and STORE are called automatically by Perl to resolve expressions like $gandalf.mana = $gandalf.mana + 5.

PerlMonks 中有更全面的讨论,包括您是否应该尝试此操作.我建议不要使用上面的 -- 和公共 rw 属性.它与其说是一个有用的工具,不如说是展示了可以用语言表达的内容.

There's a fuller discussion, including whether you should even attempt this, at PerlMonks. I would recommend against the above -- and public rw attributes in general. It's more a display of what it is possible to express in the language than a useful tool.

这篇关于如何在 Perl6 中编写自定义访问器方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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