2009-10-08 10 views
0

Store라는 클래스를 만들었다 고 가정 해 봅시다. 이 클래스에는 Name, PhoneNumber, Owner와 같은 여러 요소가 있습니다.클래스의 두 인스턴스를 비교하는 방법

이 클래스의 인스턴스를 2 개 생성했으며 어떤 값이 다른지 알고 싶습니다.

그래서 Store1과 Store2가이 클래스의 인스턴스라고 가정 해 보겠습니다. 보통

Store1.Name = "John's Corner"; 
Store1.PhoneNumber = 111222333; 
Store1.Owner = "John"; 

Store2.Name = "John's Corner"; 
Store2.PhoneNumber = 444555666; 
Store2.Owner = "John"; 

하나 할 것입니다 비교 :
if (Store1.Name == Store2.Name) output.text += "Store name is different." 
if (Store1.PhoneNumber == Store2.PhoneNumber) output.text += "Store Phone Number is different." 
if (Store1.Owner == Store2.Owner) output.text += "Store Owner is different." 

자동으로 클래스 인스턴스의 모든 요소를 ​​통해 루프 어떤 때를 다른 클래스의 인스턴스에서 같은 요소를 비교하고 반환 할 수있는 방법이 있나요 그들은 다르다?

이것은 분명 할 수도 있지만 알아낼 수는 없습니다.

답변

2

:

var typeXML:XML = describeType(Store1); 
var diffs:Dictionary = new Dictionary(); 
for each(var prop:XML in type..accessor){ 
    if(Store1[prop] != Store2[prop]){ 
      diffs[prop] = new Array(Store1[prop],Store2[prop]); 
    } 
} 

죄송 내 앞에 컴파일러가없는 그래서 난이 중 하나를 확인할 수 없습니다. for 루프에서 루프 할 대상을 확인하려면 typeXML 객체를 살펴보십시오. 제임스의 코드에 따라

+0

+1은'describeType'에 대해 생각 나게합니다. type.accessor가 충분하지 않으면 type.variable도 확인해야합니다. 또한 접근 자만 쓰는 것을 피해야합니다. 그렇지 않으면 예외가있을 수 있습니다. – Amarghosh

+0

describeType을 사용하여 두 객체를 비교하는 함수로 내 대답을 업데이트했습니다. 나는 너무 많은 자유 시간을 내가 짐작한다 :) – Amarghosh

+0

이것은 내가 찾던, 고마워. – Nodja

0

매장 한 두 개의 서로 다른 유형의 경우 분명히이 작동하지 않습니다

for (var property in Store1) 
{ 
    if (Store1[property] == Store2[property]) 
    { 
     trace("property-" + property + ", value-" + Store1[property]); 
    } 
} 

보십시오. 당신이 그것의 accesors에서 입력 한 다음 루프를 설명 할 수 밀봉 속성의

+0

for..in 구문은 동적 속성에서만 작동합니다. 객체의 봉인 된 속성을 통해 반복되지 않습니다. 그렇습니까? – Amarghosh

+0

아, 예 ... 방금 테스트를 마쳤습니다. 봉인 된 속성에는 작동하지 않습니다. –

0

,이에 첫 번째 라인을 변경할 수 있습니다 : 당신이 그것을 할 필요가있는 경우 동적으로 클래스의 모든 공용 속성을 검색 할 describeType를 사용할 수

for (var property in ["property1","property2","property3") 

.

0

완전히 일반적인 해결책 (몇개의 클래스를 비교할 것인가?)을 원하지 않는다면 클래스 속성을 거치며 부울 값을 반환하는 각각의 클래스에 사용자 정의 compare 함수를 작성하십시오.

업데이트 :
describeType에게 감사합니다. describeType에주의해야하는 한 가지 점은 클래스의 공용 변수/속성 만 반영한다는 것입니다. private/protected/internal stuff는 describeType의 출력에 포함되지 않습니다. 따라서이 속성을 사용하여 동일한 공용 속성은 있지만 다른 개인 속성을 가진 두 개체를 비교하면 여전히 동일한 것으로 표시됩니다.

다음은 AS 클래스 및 describeType 출력입니다. Data.as

package 
{ 
    public class Data 
    { 
     private var privateVar:Boolean; 
     protected var protectedVar:Boolean; 
     internal var internalVar:Boolean; 
     var noModifierVar:Boolean; 
     public var publicVar:Boolean; 

     public function set writeOnlyProp(value:Boolean):void 
     { 
     } 

     public function get readOnlyProp():Boolean 
     { 
      return true; 
     } 

     public function set readWriteProp(value:Boolean):void 
     { 

     } 
     public function get readWriteProp():Boolean 
     { 
      return false; 
     } 

     public function Data(pub:Boolean = false, priv:Boolean = false, 
      prot:Boolean = false, inter:Boolean = false) 
     { 
      this.privateVar = priv; 
      this.protectedVar = prot; 
      this.internalVar = inter; 
      this.publicVar = pub; 
     } 
    } 
} 

describeType의 출력 : 공공의 변수가 여기에 나열되어 있는지 확인합니다.

public static function compareObjects(a:Object, b:Object):Boolean 
{ 
    var description:XML = describeType(a); 
    var bDescription:XML = describeType(b); 
    //different classes 
    if(description.toXMLString() != bDescription.toXMLString()) 
     return false; 
    if(String([email protected]) == "true") 
    { 
     var t:*; 
     for(t in a) 
      if(a[t] != b[t]) 
       return false; 
     //Just in case b has a dynamic property that a doesn't 
     for(t in b) 
      if(a[t] != b[t]) 
       return false; 
    } 
    var properties:Array = []; 
    //readonly and readwrite properties 
    var accessors:XMLList = description.accessor.(@access != "writeonly"); 
    var type:XML; 
    for each(type in accessors) 
     properties.push(String([email protected])); 
    //other variables 
    var variables:XMLList = description.variable; 
    for each(type in variables) 
     properties.push(String([email protected])); 
    for each(var prop:String in properties) 
    { 
     if(a[prop] != b[prop]) 
      return false; 
    } 
    return true; 
} 

PS :

<type name="Data" base="Object" isDynamic="false" isFinal="false" isStatic="false"> 
    <extendsClass type="Object"/> 
    <constructor> 
    <parameter index="1" type="Boolean" optional="true"/> 
    <parameter index="2" type="Boolean" optional="true"/> 
    <parameter index="3" type="Boolean" optional="true"/> 
    <parameter index="4" type="Boolean" optional="true"/> 
    </constructor> 
    <accessor name="readOnlyProp" access="readonly" type="Boolean" declaredBy="Data"/> 
    <variable name="publicVar" type="Boolean"/> 
    <accessor name="readWriteProp" access="readwrite" type="Boolean" declaredBy="Data"/> 
    <accessor name="writeOnlyProp" access="writeonly" type="Boolean" declaredBy="Data"/> 
</type> 

일반적인 비교 코드는 같을 것이다 나는 아직도 각각의 클래스에 사용자 지정 코드를 작성하는 것은 아무튼이 같이 갈 수있는 올바른 방법이라고 생각이 모든 코드를 작성 후 ' 개인/보호 된 데이터를 고려하십시오.

0

두 개체를 JSON 문자열로 serialize하고 문자열 비교를 수행하면됩니다.

관련 문제