Вот два метода расширения для использования
public static Type FindInterfaceWith(this Type type1, Type type2) {
// returns most suitable common implemented interface
}
public static Type FindBaseClassWith(this Type type1, Type type2) {
// returns most derivative of common base class
}
-
FindInterfaceWith
возвращаетnull
, если у них нет общего реализованного интерфейса. -
FindBaseClassWith
возвращаетSystem.Object
, если у них нет более производного общего базового класса. -
FindBaseClassWith
возвращаетnull
, если один из параметров был интерфейсом. - Оба они возвращают
null
, если любой из параметров былnull
.
И подпись метода в окончательном решении будет выглядеть так:
public static Type FindAssignableWith(this Type type1, Type type2) {
// what should be here?
}
Отражение и Linq ограничены в использовании, кроме других способов.
Есть ли хорошие способы найти наилучшее соответствие общего типа между type1
и type2
?
Или есть что-то лучше для этого?
обновление:
По моему личному пониманию, из-за возможности реализовать несколько интерфейсов с классом, FindInterfaceWith
возможно, потребуется вызвать FindBaseClassWith
внутренне; в противном случае лучший выбор типа был бы неразрешимым.
Если это предположение было правильным, то FindInterfaceWith
становится избыточным методом; из-за единственной разницы между FindInterfaceWith
и FindAssignableWith
является:
FindInterfaceWith
возвращает null
, если был лучший выбор класса; а FindAssignableWith
возвращает точный класс напрямую.
В противном случае оба они возвращают лучший выбор интерфейса.
Речь идет о том, что исходное предположение было иррациональным. То есть FindInterfaceWith
не может быть реализовано, если FindAssignableWith
не.