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

前端 未结 3 802
北海茫月
北海茫月 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:30

    If you look at base classes only, the problem is trivial and a solution is given by Impworks's answer ("iterating over one object's parents and checking them for being assignable with the other type").

    But if you want to include also interfaces, there's no unique solution to the problem, as you note yourself with your IDelta and ICharlie example. Two or more interfaces can easily be equally "good", so there's no single best solution. One can easily construct arbitrarily complex diagrams (graphs) of interface inheritances, and it's easy to see from such diagrams that there's no well-defined "FindAssignableWith".

    Besides, covariance/contravariance in C# are used for variance kinds of generic types. Let me give an example. Supose we have

    type1: System.Func
    type2: System.Func>
    

    then of course with base classes, the "FindAssignableWith" could be

    solutionA: System.MulticastDelegate
    

    But the type Func is also covariant (out) in its type parameter T. Therefore, the type

    solutionB: System.Func
    

    is also a solution in the sense that it IsAssignableFrom the two given types type1 and type2. But the same could be said of

    solutionC: System.Func
    

    which works because both string and Tuple<> are IComparable.

    So in the general case, there's no unique solution. So unless you specify precise rules describing what you want, we can't come up with an algorithm that finds your solution.

提交回复
热议问题