【问题标题】:Is there any function in Perl similar to GetType() in C#? [duplicate]Perl 中是否有类似于 C# 中的 GetType() 的函数? [复制]
【发布时间】:2011-01-19 05:02:49
【问题描述】:

我已经学习了一段时间 Perl,发现它与我所知道的其他 OOP 语言非常不同。 我试图翻译一个 C# 代码,如下所示:

class Car{}, class CarList{}, class Program{}

和一个方法(伪代码):

if (var.GetType() == Car)
{
}
else if (var.GetType == CarList) 
{
}

如果没有 GetType 函数,我如何在 perl 中编写这个函数?

【问题讨论】:

  • 不管是什么语言,以这种方式做事而不是多态是糟糕的 OOP。

标签: perl


【解决方案1】:

在很多 Perl 代码中,ref 运算符是您在寻找对象类的确切名称时所需要的。由于如果值不是引用则未定义,因此您需要在使用字符串比较之前检查该值。

if(ref $var) {
    if(ref($var) eq 'Car') {
        # ...
    } elsif(ref($var) eq 'CarList') {
        # ...
    }
}

您更有可能想要 C# 的 is 运算符之类的东西。那就是UNIVERSALisa 方法,它被所有对象继承。来自http://perldoc.perl.org/UNIVERSAL.html 文档的示例:

use Scalar::Util 'blessed';

# Tests first whether $obj is a class instance and second whether it is an
# instance of a subclass of Some::Class
if ( blessed($obj) && $obj->isa("Some::Class") ) {
    ...
}

【讨论】:

  • 不错! isa 更接近 GetType。
【解决方案2】:

ref 应该是你需要的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-29
    • 2021-02-02
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 2013-01-03
    • 1970-01-01
    • 2011-02-27
    相关资源
    最近更新 更多