[英]How to check the type of a parameter in Haxe
I'm converting a JavaScript library to Haxe. 我正在将一个JavaScript库转换为Haxe。 It seems Haxe is very similar to JS, but in working I got a problem for function overwriting. 似乎Haxe与JS非常相似,但在工作中我遇到了覆盖函数的问题。
For example, in the following function param
can be an an integer or an array. 例如,在下面的函数中, param
可以是整数或数组。
JavaScript: 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');
}
}
Haxe: HAXE:
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');
}
}
Of course Haxe supports Type.typeof()
but there isn't any ValueType
for Array
. 当然Haxe支持Type.typeof()
但是没有任何ValueType
for Array
。 How can I solve this problem? 我怎么解决这个问题?
In Haxe, you'd usually use Std.is()
for this instead of Type.typeof()
: 在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');
}
It's possible to use Type.typeof()
as well, but less common - you can use pattern matching for this purpose. 也可以使用Type.typeof()
,但不太常见 - 您可以使用模式匹配来实现此目的。 Arrays are of ValueType.TClass
, which has a c:Class<Dynamic>
parameter: 数组是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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.