如何将类属性声明为类名的联合? [英] How do I declare a class attribute as a union of class names?

查看:41
本文介绍了如何将类属性声明为类名的联合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一个寻找不同结构的电子表格.当我使用 Moose 尝试以下操作时,它似乎可以满足我的要求.我可以创建不同类型的对象,将其分配给找到的成员并转储 Cell 实例以供审查.

封装 Cell{使用驼鹿;使用 Moose::Util::TypeConstraints;使用命名空间::自动清理;有 'str_val' =>( is => 'ro', isa => 'Str', required => 1 );有 'x_id' =>( is => 'ro', isa => 'Str', );# 稍后需要 =>1);有颜色"=>( is => 'ro', isa => 'Str', );有边界"=>( is => 'ro', isa => 'Str', );有发现"=>( is => 'rw', isa => 'Sch_Symbol|Chip_Symbol|Net', );1;}

如果我尝试在 Perl 6 中做同样的事情,它会编译失败.

class Cell {有 Str $.str_val 是必需的;有 Str $.x_id 是必需的;有 Str $.color;有 Str $.border;有 Sch_Symbol|Chip_Symbol|Net $.found 是 rw}

<块引用>

格式错误的有在 C:\Users\Johan\Documents/moose_sch_3.pl6:38------>has Sch_Symbol'<'HERE'>'|Chip_Symbol|Net $.found 是 rw

我怎样才能在 Perl 6 中做到这一点?

解决方案

您可以使用 where

有 $.found 是 rw 其中 Sch_Symbol|Chip_Symbol|Net;

或通过subset 定义新类型>

subset Stuff where Sch_Symbol|Chip_Symbol|Net;类细胞{有 Str $.str_val 是必需的;有 Str $.x_id 是必需的;有 Str $.color;有 Str $.border;有东西 $.found 是 rw;}

I'm reading a spreadsheet looking for different structures. When I tried the following using Moose it seems to do what I want. I could create different types of objects, assign this to the found member and dump the Cell instance for review.

package Cell
{
  use Moose;
  use Moose::Util::TypeConstraints;
  use namespace::autoclean;

  has 'str_val'    => ( is => 'ro', isa => 'Str', required => 1 );
  has 'x_id'       => ( is => 'ro', isa => 'Str', ); # later required => 1 );
  has 'color'      => ( is => 'ro', isa => 'Str', );
  has 'border'     => ( is => 'ro', isa => 'Str', );
  has 'found'      => ( is => 'rw', isa => 'Sch_Symbol|Chip_Symbol|Net', );
  1;
}

If I try to do the same in Perl 6 it fails to compile.

class Cell {
  has Str $.str_val              is required;
  has Str $.x_id                 is required;
  has Str $.color;
  has Str $.border;
  has Sch_Symbol|Chip_Symbol|Net $.found is rw
}

Malformed has
at C:\Users\Johan\Documents/moose_sch_3.pl6:38
------>   has Sch_Symbol'<'HERE'>'|Chip_Symbol|Net $.found is rw

How can I do this in Perl 6?

解决方案

You could use where

has $.found is rw where Sch_Symbol|Chip_Symbol|Net;

or define new type by subset

subset Stuff where Sch_Symbol|Chip_Symbol|Net;

class Cell {
    has Str   $.str_val is required;
    has Str   $.x_id    is required;
    has Str   $.color;
    has Str   $.border;
    has Stuff $.found   is rw;
}

这篇关于如何将类属性声明为类名的联合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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