Created
December 2, 2020 10:49
-
-
Save hsytkm/f038f0014809477f3e9d99f11bf6ad73 to your computer and use it in GitHub Desktop.
Manage multiple id.
This file contains 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
// 複数のIDを管理するテク | |
// 【C# 9.0】 Source Generator回 - ufcpp https://youtu.be/QXT-TSvIbbY?t=5816 | |
var person0 = new Person(0); | |
var person1 = new Person(1); | |
var shop0 = new Shop(0); | |
System.Console.WriteLine("Check Id0 : " + (person0.Id == person1.Id)); | |
// 以下だと型が違うので比較できない | |
//System.Console.WriteLine("Check Id1 : " + (person0.Id == shop0.Id)); | |
// 無理やりキャストすれば比較できんこともない | |
System.Console.WriteLine("Check Id2 : " + ((int)person0.Id == (int)shop0.Id)); | |
class Person | |
{ | |
public Id<Person> Id { get; init; } | |
public Person(int id) => Id = new Id<Person>(id); | |
} | |
class Shop | |
{ | |
public Id<Shop> Id { get; init; } | |
public Shop(int id) => Id = (Id<Shop>)id; | |
} | |
public struct Id<T> : System.IEquatable<Id<T>> | |
{ | |
public readonly int Value { get; init; } | |
public Id(int value) => Value = value; | |
public static bool Equals(Id<T> left, Id<T> right) => left.Value == right.Value; | |
public readonly bool Equals(Id<T> other) => Equals(this, other); | |
public readonly override bool Equals(object? obj) => obj is Id<T> other && Equals(this, other); | |
public readonly override int GetHashCode() => Value.GetHashCode(); | |
public static bool operator ==(Id<T> left, Id<T> right) => Equals(left, right); | |
public static bool operator !=(Id<T> left, Id<T> right) => !Equals(left, right); | |
public static explicit operator Id<T>(int value) => new Id<T>() { Value = value }; | |
public static explicit operator int(Id<T> value) => value.Value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment