How to find the minimum covariant type for best fit between two types?

前端 未结 3 803
北海茫月
北海茫月 2020-12-03 14:03

There\'s IsAssignableFrom method returns a boolean value indicates if one type is assignable from another type.

How can we not only test if they are as

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 14:17

    The simplest case would be iterating over the base types of one object and checking them for being assignable with the other type, like this:

    • Code

      public Type GetClosestType(Type a, Type b) {
          var t=a;
      
          while(a!=null) {
              if(a.IsAssignableFrom(b))
                  return a;
      
              a=a.BaseType;
          }
      
          return null;
      }
      

    This will produce System.Object for two types which are unrelated, if they are both classes. I'm not sure if this behaviour met your requirement.

    For more advanced cases, I'm using a custom extension method called IsExtendablyAssignableFrom.

    It can handle different numeric types, generics, interfaces, generic parameters, implicit conversions, nullable, boxing/unboxing, and pretty much all the types I have come across with when implementing my own compiler.

    I've uploaded the code into a separate github repository [here], so you could use it in your project.

提交回复
热议问题