From 08bfc168041c58cc2e6672ad770ce592e253f837 Mon Sep 17 00:00:00 2001 From: syneffort Date: Thu, 29 Feb 2024 17:47:33 +0900 Subject: [PATCH] generic compatible --- EffectiveCSharp/EffectiveCSharp/Program.cs | 10 ++++-- .../UseGeneric/GenericCompatible.cs | 35 +++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) create mode 100644 EffectiveCSharp/EffectiveCSharp/UseGeneric/GenericCompatible.cs diff --git a/EffectiveCSharp/EffectiveCSharp/Program.cs b/EffectiveCSharp/EffectiveCSharp/Program.cs index 31ed4be..d2685ab 100644 --- a/EffectiveCSharp/EffectiveCSharp/Program.cs +++ b/EffectiveCSharp/EffectiveCSharp/Program.cs @@ -1,4 +1,5 @@ using EffectiveCSharp.LanguageComponent; +using EffectiveCSharp.UseGeneric; namespace EffectiveCSharp { @@ -6,9 +7,12 @@ namespace EffectiveCSharp { static void Main(string[] args) { - CallEvent callEvent = new CallEvent(); - callEvent.Event += (s, e) => Console.WriteLine(e); - callEvent.Work(); + GenericCompatible.AreEqual(new { test = 1 }, new { test = 2 }); + GenericCompatible.BetterAreEqual(new { test = 1 }, new { test = 2 }); // 컴파일 타임 체크 가능 + + //CallEvent callEvent = new CallEvent(); + //callEvent.Event += (s, e) => Console.WriteLine(e); + //callEvent.Work(); } } diff --git a/EffectiveCSharp/EffectiveCSharp/UseGeneric/GenericCompatible.cs b/EffectiveCSharp/EffectiveCSharp/UseGeneric/GenericCompatible.cs new file mode 100644 index 0000000..cb74c9c --- /dev/null +++ b/EffectiveCSharp/EffectiveCSharp/UseGeneric/GenericCompatible.cs @@ -0,0 +1,35 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace EffectiveCSharp.UseGeneric +{ + internal class GenericCompatible + { + public static bool AreEqual(T left, T right) + { + if (left == null) + return right == null; + + if (left is IComparable) + { + IComparable lval = left as IComparable; + if (right is IComparable) + return lval.CompareTo(right) == 0; + else + throw new ArgumentException("Type does not implement IComparable", nameof(right)); + } + else + { + throw new ArgumentException("Type does not implement IComparable", nameof(left)); + } + } + + public static bool BetterAreEqual(T left, T right) where T : IComparable + { + return left.CompareTo(right) == 0; + } + } +}