generic compatible

main
syneffort 1 year ago
parent 690b0d05c6
commit 08bfc16804
  1. 10
      EffectiveCSharp/EffectiveCSharp/Program.cs
  2. 35
      EffectiveCSharp/EffectiveCSharp/UseGeneric/GenericCompatible.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();
}
}

@ -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>(T left, T right)
{
if (left == null)
return right == null;
if (left is IComparable<T>)
{
IComparable<T> lval = left as IComparable<T>;
if (right is IComparable<T>)
return lval.CompareTo(right) == 0;
else
throw new ArgumentException("Type does not implement IComparable<T>", nameof(right));
}
else
{
throw new ArgumentException("Type does not implement IComparable<T>", nameof(left));
}
}
public static bool BetterAreEqual<T>(T left, T right) where T : IComparable<T>
{
return left.CompareTo(right) == 0;
}
}
}
Loading…
Cancel
Save