Free cookie consent management tool by TermsFeed Policy Generator

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

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

#3026:

  • changed the namespace from ParameterTest to HeuristicLab.Manufacture
  • added an extension method for Type to get the distance of an interface based on the target type
  • renamed methods ToData, SetValue to Extract, Inject
  • new implementation of the template generation with transformers (not the final name)
  • started to use the new transformers for the instantiation of IOptimizer-objects (out of a template)
  • new transformers: LookupParameterTransformer and DummyTransformer
File size: 2.0 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using System.Threading.Tasks;
6
7namespace HeuristicLab.Manufacture {
8  public static class TypeExtensions {
9    public static int GetInterfaceDistance(this Type type, Type interfaceType) {
10      if (!interfaceType.IsInterface) return -1;
11      int distance = 0;
12      Type baseType = type;
13      while (baseType != typeof(object)) {
14        var interfaces = baseType.GetInterfaces();
15        var minimalInterfaces = interfaces.Except(interfaces.SelectMany(i => i.GetInterfaces()));
16        if (baseType == interfaceType && minimalInterfaces.Any(i => i == interfaceType))
17          ++distance;
18        baseType = baseType.BaseType;
19      }
20      return distance;
21    }
22    public static bool IsEqualTo(this Type type, Type other) {
23      if (other == null) throw new ArgumentNullException("other");
24      if (type == other) return true;
25      if (other.IsInterface && other.IsGenericType)
26        return
27          type.IsAssignableFrom(other) ||
28          type.GetInterfaces()
29            .Where(i => i.IsGenericType)
30            .Any(i => i.GetGenericTypeDefinition() == other);
31      else if (other.IsInterface) {
32        /*
33        Type baseType = type;
34        while (baseType != typeof(object)) {
35          var interfaces = baseType.GetInterfaces();
36          var minimalInterfaces = interfaces.Except(interfaces.SelectMany(i => i.GetInterfaces()));
37          if (baseType == other && minimalInterfaces.Any(i => i == other))
38            return true;
39          baseType = baseType.BaseType;
40        }
41        */
42        return type.GetInterfaces().Any(i => i == other);
43      }
44       
45      else if (other.IsGenericType) {
46        Type baseType = type;
47        while (baseType != typeof(object)) {
48          if (baseType.IsGenericType && baseType.GetGenericTypeDefinition() == other)
49            return true;
50          baseType = baseType.BaseType;
51        }
52      }
53      return type.IsAssignableFrom(other);
54    }
55  }
56}
Note: See TracBrowser for help on using the repository browser.