Free cookie consent management tool by TermsFeed Policy Generator

source: branches/3026_IntegrationIntoSymSpace/HeuristicLab.Manufacture/Extensions/TypeExtensions.cs @ 17269

Last change on this file since 17269 was 17269, checked in by dpiringe, 5 years ago

#3026

  • deleted IItemExtensions.cs
  • fixed a bug in GetInterfaceDistance in TypeExtensions.cs -> generic types were ignored
  • lots of code clean ups
  • added new transformers: ParameterizedItemTransformer, MultiCheckedOperatorTransformer
File size: 1.7 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading.Tasks;
6using HeuristicLab.Core;
7
8namespace HeuristicLab.Manufacture {
9  public static class TypeExtensions {
10    public static int GetInterfaceDistance(this Type type, Type interfaceType) {
11      if (!interfaceType.IsInterface) return -1;
12      int distance = int.MaxValue;
13      Type baseType = type;
14      while (baseType != typeof(object)) {
15        var interfaces = baseType.GetInterfaces();
16        var minimalInterfaces = interfaces.Except(interfaces.SelectMany(i => i.GetInterfaces()));
17        if (minimalInterfaces.Any(i => {
18          if (i.IsGenericType)
19            return i.GetGenericTypeDefinition() == interfaceType;
20          return i == interfaceType;
21        })) --distance;
22        baseType = baseType.BaseType;
23      }
24      return distance;
25    }
26
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}
Note: See TracBrowser for help on using the repository browser.