Created
March 20, 2020 06:41
-
-
Save werwolfby/237fb8c5c38fe2877250af85e94e9cd8 to your computer and use it in GitHub Desktop.
Search type (base or interface) in type with ability to search concrete type by generic type definition
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; | |
namespace DataAccess | |
{ | |
public static class TypeExtensions | |
{ | |
public static Type? SearchType(this Type type, Type searchType) | |
{ | |
return searchType.IsInterface | |
? SearchInterfaceType(type, searchType) | |
: SearchBaseType(type, searchType); | |
static Type? SearchInterfaceType(Type type, Type searchType) | |
{ | |
foreach (var interfaceType in type.GetInterfaces()) | |
{ | |
var searchedType = CompareType(interfaceType, searchType); | |
if (searchedType != null) | |
{ | |
return searchType; | |
} | |
} | |
return null; | |
} | |
static Type? SearchBaseType(Type type, Type searchType) | |
{ | |
Type? currentType = type; | |
while (currentType != null) | |
{ | |
var searchedType = CompareType(currentType, searchType); | |
if (searchedType != null) | |
{ | |
return searchType; | |
} | |
currentType = currentType.BaseType; | |
} | |
return null; | |
} | |
static Type? CompareType(Type type, Type searchType) | |
{ | |
var compareType = type; | |
if (searchType.IsGenericTypeDefinition && type.IsGenericType) | |
{ | |
compareType = type.GetGenericTypeDefinition(); | |
} | |
return compareType == searchType ? type : null; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment