스토리지

[3.18] GUID 및 Equatable 본문

Unity/수업내용(C#)

[3.18] GUID 및 Equatable

ljw4104 2021. 3. 18. 11:28

1. Guid.newGuid()

 

Guid.NewGuid 메서드 (System)

Guid 구조체의 새 인스턴스를 초기화합니다.Initializes a new instance of the Guid structure.

docs.microsoft.com

2. Equatable<T>

  • 객체가 컬렉션안에 있는지 판별할 때 IEquatable<T>의 함수를 오버라이딩을 해서 비교를 함
  • Contains로 참조객체 비교할 때 가리키는 곳, 즉 주소가 같지 않으면 false를 리턴하기 때문에 멤버값들을 비교해줘야됨.
  • docs.microsoft.com/ko-kr/dotnet/api/system.iequatable-1.equals?view=net-5.0
  • 이것을 사용하기에 컬렉션을 foreach로 순회할 수 있음.
 

IEquatable.Equals(T) 메서드 (System)

현재 개체가 동일한 형식의 다른 개체와 같은지 여부를 나타냅니다.Indicates whether the current object is equal to another object of the same type.

docs.microsoft.com

using System;
using System.Collections.Generic;

namespace Study07
{
    public class App
    {
        public App()
        {
            //Unit객체 생성
            Unit unit1 = new Unit("2b1e83fe-ddcd-4257-9e9a-1bbb4635ed0d", "홍길동");
            Unit unit2 = new Unit("3547be87-d696-4d0b-b37b-2e30517a6c5d", "임꺽정");
            Unit unit3 = new Unit("4846e7a1-2283-49c2-b128-4c423216ce0a", "장길산");

            List<Unit> units = new List<Unit>();
            units.Add(unit1);
            units.Add(unit2);
            units.Add(unit3);

            Unit unit = new Unit("2b1e83fe-ddcd-4257-9e9a-1bbb4635ed0d", "홍길동");
            if (units.Contains(unit))
            {
                Console.WriteLine("Found {0}, id : {1}", unit.Name, unit.Id);
            }
            else
            {
                Console.WriteLine("[Not Found] id : {0}", unit.Id);
            }
        }
    }
}
using System;
using System.Collections.Generic;

namespace Study07
{
    public class Unit : IEquatable<Unit>
    {
        public string Id
        {
            get; private set;
        }

        public string Name
        {
            get; set;
        }

        public Unit(string id, string name)
        {
            this.Id = id;
            this.Name = name;
            Console.WriteLine("Unit 생성자 호출 : {0}, {1}", this.Id, this.Name);
        }

        public bool Equals(Unit other)
        {
        	//매개변수가 null이 아니고 id와 name이 서로 같으면?
            return other != null && this.Id == other.Id && this.Name == other.Name ? true : false;
        }

        public override bool Equals(object obj)
        {
            if (obj == null)
                return false;

            Unit unitObj = obj as Unit;
            //Object 형식으로 들어왔기 때문에 Unit형태로 unboxing해줌
            if (unitObj == null)
                return false;


            return base.Equals(unitObj);
        }
    }
}

@ IEquatable 인터페이스 미적용시

 

@ IEquatable 인터페이스 적용시

'Unity > 수업내용(C#)' 카테고리의 다른 글

[3.18] 2차원 배열 연습 1  (0) 2021.03.18
[3.18] Indexer  (0) 2021.03.18
[3.17] Queue 연습 1  (0) 2021.03.17
[3.17] Stack 연습 1  (0) 2021.03.17
[3.17] 인터페이스 연습 2  (0) 2021.03.17
Comments