3

我有一个组成鼠标角色的 Moose 类。

package My::Moose::Class;
use Moose;
has 'mouse_obj' => (
    is   => 'ro',
    does => 'NotMy::Mouse::Role',
);

package NotMy::Mouse::Role;
use Mouse::Role;

package NotMy::Mouse::Class;
use Mouse;
with 'NotMy::Mouse::Role';

这将得到一个错误,因为 Mouse 角色在 Moose 中未被识别为一种类型:

my $f = My::Moose::Class->new( mouse_obj => NotMy::Mouse::Class->new );

属性 (mouse_obj) 未通过类型约束,因为: 'NotMy::Mouse::Role' 的验证失败,值为 NotMy::Mouse::Class=HASH(0x23932dc) (not isa NotMy::Mouse::Role) at ...

有哪些方法可以在不将鼠标对象更改为 Moose 的情况下使其工作?

4

1 回答 1

1

您可以这样做的一种方法是创建一个自定义类型约束来执行您想要的检查。

use Moose::Util::TypeConstraints;

subtype 'MouseRole'
    => as 'Object'
    => where sub { $_->does('NotMy::Mouse::Role') };

has 'mouse_obj' => (
    is   => 'ro',
    isa => 'MouseRole', # "isa" not "does"!
);
于 2012-06-24T00:43:45.940 回答