-
-
Save oguzhaneren/33e1be86430f34093b5b0c4bffb73a7f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace [YOURNAMESPACEHERE] | |
{ | |
public static class TypeExtensions | |
{ | |
public static bool IsDerivingFrom(this Type type, Type searchType) | |
{ | |
if (type == null) throw new NullReferenceException(); | |
return | |
type.BaseType != null && | |
(type.BaseType == searchType || | |
type.BaseType.IsDerivingFrom(searchType)); | |
} | |
public static bool IsDerivingFromGenericType(this Type type, Type searchGenericType) | |
{ | |
if (type == null) throw new ArgumentNullException(nameof(type)); | |
if (searchGenericType == null) throw new ArgumentNullException(nameof(searchGenericType)); | |
return | |
type != typeof(object) && | |
(type.IsGenericType && | |
searchGenericType.GetGenericTypeDefinition() == searchGenericType || | |
IsDerivingFromGenericType(type.BaseType, searchGenericType)); | |
} | |
[System.Diagnostics.CodeAnalysis.SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Extension method")] | |
public static Type GetItemType<T>(this IEnumerable<T> enumerable) => typeof(T); | |
public static Type? GetItemType(this object enumerable) | |
=> enumerable == null ? null : | |
(enumerable.GetType().GetInterface(typeof(IEnumerable<>).Name)?.GetGenericArguments()[0]); | |
public static bool ImplementsInterface(this Type? type, Type? @interface) | |
{ | |
bool result = false; | |
if (type == null || @interface == null) | |
return result; | |
var interfaces = type.GetInterfaces(); | |
if (@interface.IsGenericTypeDefinition) | |
{ | |
foreach (var item in interfaces) | |
{ | |
if (item.IsConstructedGenericType && item.GetGenericTypeDefinition() == @interface) | |
result = true; | |
} | |
} | |
else | |
{ | |
foreach (var item in interfaces) | |
{ | |
if (item == @interface) | |
result = true; | |
} | |
} | |
return result; | |
} | |
public static Type? FindType(this string name) | |
{ | |
Type? result = null; | |
var nonDynamicAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic); | |
try | |
{ | |
result = nonDynamicAssemblies. | |
SelectMany(a => a.GetExportedTypes()). | |
FirstOrDefault(t => t.Name == name); | |
} | |
catch | |
{ | |
result = nonDynamicAssemblies. | |
SelectMany(a => a.GetTypes()). | |
FirstOrDefault(t => t.Name == name); | |
} | |
return result; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment