본문 바로가기
프로그래밍

개체 비교 함수

by minimax95 2020. 7. 7.

이번 포스팅에서는 개체를 비교하는 몇 가지 방법에 대해서 알아보겠습니다.

 

보통 개체 비교를 위해 IComparable 인터페이스를 구현하여 CompareTo( ) 함수를 이용하지만 여기서는 object를 바이너리로 변환하여 비교하는 방법과 object의 ReferenceEquals( ) 함수를 이용한 방법에 대해서 살펴보겠습니다.

 

먼저 object를 바이너리로 변환하여 비교하는 방법입니다.

함수의 원형은 아래와 같습니다.

bool CheckEquals(object source, object target);

 

매개변수로 두 개의 object를 받아서 내부에서 바이너리로 변환, 비교한 후 결과를 반환하는 함수입니다.

함수의 구현은 아래와 같습니다.

bool CheckEquals(object source, object target)

{

    BinaryFormatter bf1 = new BinaryFromatter( );

    MemoryStream ms1 = new MemoryStream( );

    bf1.Serialize(ms1, source); 

 

    BinaryFormatter bf2 = new BinaryFromatter( );

    MemoryStream ms2 = new MemoryStream( );

    bf2.Serialize(ms2, target); 

 

    byte[ ] array1 = ms1.ToArray( );

    byte[ ] array2 = ms2.ToArray( );

 

    if(array1.Length != array2.Length)

        return false;

 

    for(int i = 0; i < array1.Length; ++i)

    {

        if(array1[i] != array2[i])

            return false;

    }

    return ture;

}

 

개체를 비교하는 두 번째 방법으로 object의 ReferenceEquals( ) 함수를 사용해 보겠습니다.

함수의 원형은 아래와 같이 만들어보았습니다.

bool CheckValuePairEquals(KeyValuePair<string, string>[ ] value, KeyValuePair<string, string>[ ] compareValue);

<Key, Value> 형태로 되어 있는 두 개의 매개변수를 인자로 받아 내부에서 개체 비교 후 결과를 반환하는 기능을 구현해 보겠습니다. 

 

bool CheckValuePairEquals(KeyValuePair<string, string>[ ] value, KeyValuePair<string, string>[ ] compareValue)

{

    bool bResult = true;

 

    if(object.ReferenceEquals(value, compareValue))

    {

        bResult = true;    // 같은 개체

    }

    else if(value == null || compareValue == null || value.Length != compareValue.Length)

    {

        bResult = false;    // 개체가 null이거나 요소의 수가 다를 경우 false 반환

    }

    else

    {

        for(int i = 0; i < value.Length; ++i)

        {

            if(!value[i].Equals(compareValue[i]))

            {

                bResult = false;    // 1개라도 같지 않은 요소가 있으면 false 반환

                break;

            }

        }

    }

    return bResult;

}

 

이상으로 개체 비교 함수에 대한 포스팅을 마치겠습니다.

감사합니다.

 

 

댓글