另一个ActionScript新手错误1118:使用静态类型Object将值隐式强制转换为可能的

时间:2012-02-26 04:26:56

标签: flex actionscript

编译AS3 / Flex项目时出现此错误:

Error 1118: Implicit coercion of a value with static type Object to a possibly 
unrelated type HRPeople

我已经明确声明dataHR_A属于HRPeople类,我已经初始化了HRPeople.as文件中的所有数组。不知道为什么我会收到这个错误。

我的MXML代码看起来像(摘录):

<?xml version="1.0" encoding="utf-8"?>
<s:Application 
    creationComplete="initApp()"
    xmlns:fx="http://ns.adobe.com/mxml/2009"
    xmlns:s="library://ns.adobe.com/flex/spark"
    xmlns:mx="library://ns.adobe.com/flex/mx">

    <fx:Script>
        <![CDATA[                   
            public var dataHR_A:HRPeople = new HRPeople;

            public function initApp():void
            {               
                //preallocate memory
                dataHR_A.elements = 5;
                dataHR_A.FirstName = new Array(dataHR_A.elements);
                dataHR_A.LastName = new Array(dataHR_A.elements);
                dataHR_A.Email = new Array(dataHR_A.elements);
                dataHR_A.Salary = new Array(dataHR_A.elements);

                dataHR_A = {  // ERROR IS ON THIS LINE OF CODE
                    FirstName:["Donald","Douglas","Jennifer","Michael","Pat"],
                    LastName:["OConnell","Grant","Whalen","Hartstein","Fay"],
                    Email:["OCONNELL","DGRANT","JWHALEN","MHARTSTE","PFAY"],
                    Salary:[2600, 2600, 4400, 13000, 6000]};
            }
and so on ...

这是HRPeople.as的类文件:

package {
    public class HRPeople {
        public var elements:int;
        public var FirstName:Array = [];
        public var LastName:Array = [];
        public var Email:Array = [];
        public var Salary:Array = [];
    }
}

1 个答案:

答案 0 :(得分:1)

您无法在ActionScript 3中使用此类语法。因为{...}是对象而dataHR_A是HRPeople。为了使它工作,你需要这样写:

dataHR_A.elements = 5;
dataHR_A.FirstName = ["Donald","Douglas","Jennifer","Michael","Pat"];
dataHR_A.LastName = ["OConnell","Grant","Whalen","Hartstein","Fay"];
dataHR_A.Email = ["OCONNELL","DGRANT","JWHALEN","MHARTSTE","PFAY"];
dataHR_A.Salary = [2600, 2600, 4400, 13000, 6000]};

您也可以直接设置属性,不需要分配内存。

此外,您可以简单地创建一个动态获取元素数量的elements,而不是自己设置getter属性。这样您就可以添加新元素,而无需担心保持elements最新。这样的东西会起作用:

package {
    public class HRPeople {
        public function get elements():int {
            return FirstName.length;
        }
        public var FirstName:Array = [];
        public var LastName:Array = [];
        public var Email:Array = [];
        public var Salary:Array = [];
    }
}