AS3如何使变量仅保存实现给定接口的对象

时间:2014-01-23 19:25:19

标签: actionscript-3 interface typechecking

我有两个班级,分数和分数。这两个类都实现了“突出显示”。我想创建一个可以容纳不同类型对象的变量来实现“可突出显示”的界面。

var currentObject:lines; //Won't work. It can only hold 'lines' object.
var currentObject:points; //won't work because it can only hold 'points' object.
var currentObject:Object; //Won't work because it can hold any objects. I want it to hold only those objects that implements the 'highlightable' interface.

有可能吗?

由于

2 个答案:

答案 0 :(得分:5)

您需要做的就是使您的变量成为您的界面类型。

var currentObject:highlightable = new classA();

var currentObject:highlightable = new classB();

classA和classB都实现了可突出显示的界面。

答案 1 :(得分:4)

只需在类中实现界面,即可强制使用该模式。

public interface IHighlightable

public class Lines implements IHighlightable
public class Points implements IHighlightable


// for the usage you type cast as the interface
var currentObject:IHighlightable = new Lines()
var currentObject:IHighlightable = new Points()

**请务必遵循命名惯例