fork download
  1. using System;
  2.  
  3. public class Test
  4. {
  5. class ClassA
  6. {
  7. public string Value1 { get; protected set; }
  8.  
  9. // コンストラクタ
  10. public ClassA(string val) { Value1 = val; }
  11.  
  12. // == 演算子を定義
  13. public static bool operator==(ClassA self, ClassA other)
  14. {
  15. return self.Value1 == other.Value1;
  16. }
  17. // == を定義するためには != もペアで定義が必要
  18. public static bool operator!=(ClassA self, ClassA other)
  19. {
  20. return !(self == other);
  21. }
  22. }
  23.  
  24. // ClassA を継承したクラス
  25. class ClassB : ClassA
  26. {
  27. public int Value2 { get; protected set; }
  28.  
  29. public ClassB(string val1, int val2) : base(val1) { Value2 = val2; }
  30.  
  31. // == をオーバーライド?(実は出来ていない)
  32. public static bool operator==(ClassB self, ClassB other)
  33. {
  34. return self.Value1 == other.Value1 && self.Value2 == other.Value2;
  35. }
  36. // == を定義するためには != もペアで定義が必要
  37. public static bool operator!=(ClassB self, ClassB other)
  38. {
  39. return !(self == other);
  40. }
  41. }
  42.  
  43. static void Main(string[] args)
  44. {
  45. // ClassA のインスタンスを比較
  46. var a1 = new ClassA("A");
  47. var a2 = new ClassA("A");
  48.  
  49. Console.WriteLine(a1 == a2); // True
  50.  
  51. // ClassB のインスタンスを比較
  52. var b1 = new ClassB("1", 10);
  53. var b2 = new ClassB("1", 20);
  54.  
  55. Console.WriteLine(b1 == b2); // False <= Value2 の値が異なるので False
  56.  
  57. // ClassA 型の変数に代入(キャスト)
  58. ClassA c1 = b1;
  59. ClassA c2 = b2;
  60.  
  61. Console.WriteLine(c1 == c2); // True <= ここで、ClassAの==演算子が呼ばれている
  62.  
  63. Console.WriteLine($"{c1.GetType().Name}, {c2.GetType().Name}"); // ClassB, ClassB <= 実体はどちらもClassB
  64. }
  65. }
  66.  
Success #stdin #stdout 0s 131520KB
stdin
Standard input is empty
stdout
True
False
True
ClassB, ClassB