[17263] | 1 | using System;
|
---|
| 2 | using System.Collections.Generic;
|
---|
| 3 | using System.Linq;
|
---|
| 4 | using System.Text;
|
---|
| 5 | using System.Threading.Tasks;
|
---|
[17269] | 6 | using HeuristicLab.Core;
|
---|
[17263] | 7 |
|
---|
[17266] | 8 | namespace HeuristicLab.Manufacture {
|
---|
[17263] | 9 | public static class TypeExtensions {
|
---|
[17266] | 10 | public static int GetInterfaceDistance(this Type type, Type interfaceType) {
|
---|
| 11 | if (!interfaceType.IsInterface) return -1;
|
---|
[17269] | 12 | int distance = int.MaxValue;
|
---|
[17266] | 13 | Type baseType = type;
|
---|
| 14 | while (baseType != typeof(object)) {
|
---|
| 15 | var interfaces = baseType.GetInterfaces();
|
---|
| 16 | var minimalInterfaces = interfaces.Except(interfaces.SelectMany(i => i.GetInterfaces()));
|
---|
[17269] | 17 | if (minimalInterfaces.Any(i => {
|
---|
| 18 | if (i.IsGenericType)
|
---|
| 19 | return i.GetGenericTypeDefinition() == interfaceType;
|
---|
| 20 | return i == interfaceType;
|
---|
| 21 | })) --distance;
|
---|
[17266] | 22 | baseType = baseType.BaseType;
|
---|
| 23 | }
|
---|
| 24 | return distance;
|
---|
| 25 | }
|
---|
[17269] | 26 |
|
---|
[17263] | 27 | public static bool IsEqualTo(this Type type, Type other) {
|
---|
| 28 | if (other == null) throw new ArgumentNullException("other");
|
---|
| 29 | if (type == other) return true;
|
---|
| 30 | if (other.IsInterface && other.IsGenericType)
|
---|
| 31 | return
|
---|
| 32 | type.IsAssignableFrom(other) ||
|
---|
| 33 | type.GetInterfaces()
|
---|
| 34 | .Where(i => i.IsGenericType)
|
---|
| 35 | .Any(i => i.GetGenericTypeDefinition() == other);
|
---|
| 36 | else if (other.IsInterface) {
|
---|
| 37 | return type.GetInterfaces().Any(i => i == other);
|
---|
| 38 | }
|
---|
| 39 |
|
---|
| 40 | else if (other.IsGenericType) {
|
---|
| 41 | Type baseType = type;
|
---|
| 42 | while (baseType != typeof(object)) {
|
---|
| 43 | if (baseType.IsGenericType && baseType.GetGenericTypeDefinition() == other)
|
---|
| 44 | return true;
|
---|
| 45 | baseType = baseType.BaseType;
|
---|
| 46 | }
|
---|
| 47 | }
|
---|
| 48 | return type.IsAssignableFrom(other);
|
---|
| 49 | }
|
---|
| 50 | }
|
---|
| 51 | }
|
---|