From 3a2294ed2db373c64974b76566b2bcfd53e19ac9 Mon Sep 17 00:00:00 2001 From: Zoe Roux Date: Sun, 24 Jan 2021 22:46:36 +0100 Subject: [PATCH] Creating a IsOfGenericType --- Kyoo.Common/Utility.cs | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/Kyoo.Common/Utility.cs b/Kyoo.Common/Utility.cs index 4828f322..e4f7d14d 100644 --- a/Kyoo.Common/Utility.cs +++ b/Kyoo.Common/Utility.cs @@ -177,9 +177,25 @@ namespace Kyoo return obj; } - public static bool IsOfGenericType([NotNull] object obj, [NotNull] Type type) + public static IEnumerable GetInheritanceTree([NotNull] this Type type) { - throw new NotImplementedException(); + if (type == null) + throw new ArgumentNullException(nameof(type)); + for (; type != null; type = type.BaseType) + yield return type; + } + + public static bool IsOfGenericType([NotNull] object obj, [NotNull] Type genericType) + { + if (obj == null) + throw new ArgumentNullException(nameof(obj)); + if (genericType == null) + throw new ArgumentNullException(nameof(genericType)); + + IEnumerable types = genericType.IsInterface + ? obj.GetType().GetInterfaces() + : obj.GetType().GetInheritanceTree(); + return types.Any(type => type.IsGenericType && type.GetGenericTypeDefinition() == genericType); } public static object RunGenericMethod(