开发者

Compare two interfaces using "is"

开发者 https://www.devze.com 2023-04-11 03:58 出处:网络
I am not sure if I am missing something here. I would like to compare two classes that uses the same interface. Is this possible? I understand that the is operator compares classes, but is there any s

I am not sure if I am missing something here. I would like to compare two classes that uses the same interface. Is this possible? I understand that the is operator compares classes, but is there any similar function when you use interfaces?

// works
var effect1 : CrazyEffect = new CrazyEffect();
var effect2 : SaneEffect开发者_开发问答 = new SaneEffect();

trace(effect1 is effect2) // false

// does not work
var effect1 : ISoundEffect = new CrazyEffect();
var effect2 : ISoundEffect = new SaneEffect();

trace(effect1 is effect2)

1067: Implicit coercion of a value of type ISoundEffect to an unrelated type Class.


Note the differences between concepts of a class and of an object. The former is a data type whereas the latter is a runtime instance of it, a variable. is operator can not compare one variable to another.

According to language reference

is Operator

Evaluates whether an object is compatible with a specific data type, class, or interface. Use the is operator instead of the instanceof operator for type comparisons. You can also use the is operator to check whether an object implements an interface.

In other words, compiler expects the first operand to be a variable whereas the second operand should be a type identifier.

var sample:String = "Object is an instance of a class.";
     ^^^    ^^^
variable    type identifier  

However effect2 is not a type identifier but a variable. Hence the error message.

Unfortunately there is no generic operator to test for interface commonality. The only alternative is:

trace((s is ISoundEffect) && (t is ISoundEffect));

Update

Checking whether objects are instances of a same class can be done by comparing class names:

if (getQualifiedClassName(effect1) == getQualifiedClassName(effect2)) {
   // true
}

For in depth discussion see Get the class used to create an object instance in AS3


Even though it will work with getQualifiedClassName, there's a better method to check whether two objects are instances of the same class:

a['constructor'] === b['constructor']

getQualifiedClassName is very slow and CPU intensive. Since the above code just compares property values it is lightning fast. And yes, constructor IS a property of every object, however FB will complain if you try to access it using dot-notation, that's why I use dynamic property access.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号