Last active
November 6, 2024 04:58
-
-
Save s2kw/9d0bf2b8338251f4742efaf48bb88f25 to your computer and use it in GitHub Desktop.
IDをクラス化して比較可能に拡張したもの。敵のIDと武器IDをどちらもintで管理していた場合にうっかりIDというローカル変数名で混同するバグを明示的に回避するためのもの。Genericにすることでコンパイル時にエラーを出すようにしたもの。ちょっと煩雑か?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [System.Serializable] | |
| public abstract class ID<T> where T : ID<T> | |
| { | |
| [SerializeField] private int id; | |
| [SerializeField] private string identifyName; | |
| // 同じ型のみを比較可能にする | |
| public static bool operator ==(ID<T> left, ID<T> right) | |
| { | |
| if (ReferenceEquals(left, null)) | |
| return ReferenceEquals(right, null); | |
| if (ReferenceEquals(right, null)) | |
| return false; | |
| return left.id == right.id && | |
| left.identifyName == right.identifyName; | |
| } | |
| public static bool operator !=(ID<T> left, ID<T> right) | |
| { | |
| return !(left == right); | |
| } | |
| public override bool Equals(object obj) | |
| { | |
| return obj is ID<T> other && | |
| id == other.id && | |
| identifyName == other.identifyName; | |
| } | |
| public override int GetHashCode() | |
| { | |
| unchecked | |
| { | |
| int hash = 17; | |
| hash = hash * 23 + id.GetHashCode(); | |
| hash = hash * 23 + (identifyName != null ? identifyName.GetHashCode() : 0); | |
| return hash; | |
| } | |
| } | |
| } | |
| // 具体的な ID クラスの定義 | |
| public class AdditionalArmID : ID<AdditionalArmID> { } | |
| public class EnemyID : ID<EnemyID> { } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment