Skip to content

Instantly share code, notes, and snippets.

@hsytkm
Created December 2, 2020 10:49
Show Gist options
  • Save hsytkm/f038f0014809477f3e9d99f11bf6ad73 to your computer and use it in GitHub Desktop.
Save hsytkm/f038f0014809477f3e9d99f11bf6ad73 to your computer and use it in GitHub Desktop.
Manage multiple id.
// 複数の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