热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

为什么键入的可选参数的默认值为Null?-Whycan'ttypedoptionalargumentshaveadefaultofNull?

InActionScript3,whenyoudeclareanoptionalargumentbygivingitadefaultvalue,thevaluenul

In ActionScript 3, when you declare an optional argument by giving it a default value, the value null cannot be used on typed arguments.

在ActionScript 3中,当您通过为其指定默认值来声明可选参数时,null值不能用于类型化参数。

function Action(Param:int=null){
    // 1184: Incompatible default value of type Null where int is expected.
}
function Action(Param:int=0){
    // No compiler errors
} 

Any workarounds for this, or general purpose values that can apply to all data types?

此变通方法或可应用于所有数据类型的通用值的任何变通方法?

3 个解决方案

#1


You can change your int to Number and then can set it to NaN which is a special number that means 'not a number' and this can represent your null state for a Number.

您可以将int更改为Number,然后可以将其设置为NaN,这是一个特殊数字,表示“非数字”,这可以表示数字的空状态。

To check if something is NaN, you must use the isNaN() function and not val == NaN, or you will not get what you expect.

要检查某些东西是否为NaN,您必须使用isNaN()函数而不是val == NaN,否则您将无法获得预期的结果。

function Action(param:Number = NaN) : void {
    trace(param);
}

For all other objects, you can set them to null, but 'primitive' numbers are handled differently in Actionscript.

对于所有其他对象,您可以将它们设置为null,但在Actionscript中处理“原始”数字的方式不同。

#2


int variables cannot be null, that's why you get that error, only reference types like objects can be null

int变量不能为null,这就是为什么你得到那个错误,只有像对象这样的引用类型可以为null

Instead you can use NaN as a special number instead of null. If you want to check if something is NaN you mus use the isNaN function.

相反,您可以使用NaN作为特殊数字而不是null。如果你想检查是否有NaN,你可以使用isNaN函数。

#3


you could also include a flag in the method signature to avoid having the parameter promoted from int to number:

您还可以在方法签名中包含一个标志,以避免将参数从int提升为number:

function whatever(intProvided:Boolean = false, someInt:int = 0):void
{
    if(intProvided)
        doSomeStuff();
}

推荐阅读
author-avatar
n重庆商报程红Lft
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有