package { public class Person { private var _firstName:String; private var _age:int; public function get firstName():String { return _firstName; } public function set firstName(firstName:String):void { this._firstName = firstName; } public function get age():int { return _age; } public function set age(age:int):void { this._age = age; } //自定义类中应该包含一个无参构造方法,否则通过sharedObject读取该对象时会出错 // public function Person(firstName:String, age:int) { // _firstName = firstName; // _age = age; // } public function Person() { } public function toString():String { return _firstName + "的年龄是" + _age; } } }
package { import flash.display.Sprite; import flash.net.SharedObject; import flash.net.registerClassAlias; public class SerializeCustomClass extends Sprite { public function SerializeCustomClass() { registerClassAlias("Person", Person); var sharedObject:SharedObject = SharedObject.getLocal("hepeng"); if (sharedObject.data.person == undefined) { var person:Person = new Person(); person.age = 24; person.firstName = "hepeng"; sharedObject.data.person = person; trace("save person instance"); } else { trace("person instance already exists, using stored values"); } sharedObject.flush(); trace(sharedObject.data.person); } } }
原文中是采用了一个有参构造方法(已被注释掉的那部分),经本人测试,虽然可以把person存入LSO(local shared object)中,但是读取时会出问题:
经过修改,把有参构造方法去掉,添加了无参构造方法和属性的setter、getter方法。问题解决: