【问题标题】:How to check the type of a parameter in Haxe如何在 Haxe 中检查参数的类型
【发布时间】:2017-11-17 08:55:33
【问题描述】:

我正在将一个 JavaScript 库转换为 Haxe。 Haxe 看起来和 JS 很像,但是在工作中遇到了函数覆盖的问题。

例如,在以下函数中param 可以是整数或数组。

JavaScript:

function testFn(param) {
    if (param.constructor.name == 'Array') {
        console.log('param is Array');
        // to do something for Array value
    } else if (typeof param === 'number') {
        console.log('param is Integer');
        // to do something for Integer value
    } else {
        console.log('unknown type');
    }
}

斧头:

function testFn(param: Dynamic) {
    if (Type.typeof(param) == 'Array') { // need the checking here
        trace('param is Array');
        // to do something for Array value
    } else if (Type.typeof(param) == TInt) {
        trace('param is Integer');
        // to do something for Integer value
    } else {
        console.log('unknown type');
    }
}

当然,Haxe 支持Type.typeof(),但没有任何ValueType 支持Array。我该如何解决这个问题?

【问题讨论】:

    标签: arrays haxe


    【解决方案1】:

    在 Haxe 中,您通常会为此使用 Std.is() 而不是 Type.typeof()

    if (Std.is(param, Array)) {
        trace('param is Array');
    } else if (Std.is(param, Int)) {
        trace('param is Integer');
    } else {
        trace('unknown type');
    }
    

    也可以使用Type.typeof(),但不太常见 - 您可以为此目的使用pattern matching。数组是ValueType.TClass,它有一个c:Class<Dynamic>参数:

    switch (Type.typeof(param)) {
        case TClass(Array):
            trace("param is Array");
        case TInt:
            trace("param is Int");
        case _:
            trace("unknown type");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-08
      相关资源
      最近更新 更多