C#

C# System.ValueType.Equals 메서드 구현 내용 기록

DragonTory 2023. 2. 24. 21:38
반응형

 

C# System.ValueType.Equals 메서드 구현 내용 기록.

 

C++에서 memcmp()를 c#에서 구현 하려고 보니 메모리로 접근 해서 값을 비교 하려고 했더니 프로그램이 계속 죽는 문제가 발생...

C# Equals() 메서드에서 F12 눌렀더니 이런 소스가 있었네요. System.ValueType  클래스 내에 이런 내용이 있습니다. 

	public abstract class ValueType
    {
        //
        // 요약:
        //     이 인스턴스와 지정된 개체가 같은지 여부를 나타냅니다.
        //
        // 매개 변수:
        //   obj:
        //     현재 인스턴스와 비교할 개체입니다.
        //
        // 반환 값:
        //     true와 이 인스턴스가 동일한 형식이고 동일한 값을 나타내면 obj이고, 그렇지 않으면 false입니다.
        [SecuritySafeCritical]
        [__DynamicallyInvokable]
        public override bool Equals(object obj)
        {
            if (obj == null)
            {
                return false;
            }

            RuntimeType runtimeType = (RuntimeType)GetType();
            RuntimeType runtimeType2 = (RuntimeType)obj.GetType();
            if (runtimeType2 != runtimeType)
            {
                return false;
            }

            if (CanCompareBits(this))
            {
                return FastEqualsCheck(this, obj);
            }

            FieldInfo[] fields = runtimeType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            for (int i = 0; i < fields.Length; i++)
            {
                object obj2 = ((RtFieldInfo)fields[i]).UnsafeGetValue(this);
                object obj3 = ((RtFieldInfo)fields[i]).UnsafeGetValue(obj);
                if (obj2 == null)
                {
                    if (obj3 != null)
                    {
                        return false;
                    }
                }
                else if (!obj2.Equals(obj3))
                {
                    return false;
                }
            }

            return true;
        }
    }

 

이 중에 특히 FieldInfo를 얻는 부분이 핵심 내용...

FieldInfo[] fields = runtimeType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
for (int i = 0; i < fields.Length; i++)
{
       object obj2 = ((RtFieldInfo)fields[i]).UnsafeGetValue(this);
       object obj3 = ((RtFieldInfo)fields[i]).UnsafeGetValue(obj);
        if (obj2 == null)
        {
             if (obj3 != null)
             {
                  return false;
             }
        }
        else if (!obj2.Equals(obj3))
            {
                return false;
            }
       }

 }

 

 

반응형