C # Nested generics handled differently when using constraints

When using nested generics, the compiler does not work if it is used directly, but compiles correctly when using restrictions.

Example:

public static void Test1<V, E>(this Dictionary<V, E> dict)
    where V : IVertex
    where E : IEdge<V>
{}

public static void Test2(this Dictionary<IVertex, IEdge<IVertex>> dict){}

The two extension methods listed above supposedly have the same signature, but if I tried to run the code, for example:

var dict = new Dictionary<VertexInstance, EdgeInstance>();

dict.Test1();
dict.Test2();

the compiler will make a mistake in 'Test2', stating that it cannot convert to a common form with an embedded nested common. Personally, I think the syntax is Test2more intuitive.

I originally posted this as an answer in a question that asked about the differences between using common constraints and using interfaces directly, but I'm curious why this happens?

+3
1

:

, , . Dictionary<IVertex, IEdge<IVertex>> Dictionary<VertexInstance, EdgeInstance>. @Payo ; . . , , IDictionary , , IDictionary .

, . Test2 :

public static void Test2(this Dictionary<IVertex, IEdge<IVertex>> dict)
{
    dict.Add(new EvilVertex(), new EvilEdge());
} 

EvilVertex EvilEdge , VertexInstance EdgeInstance. . Test2 , .

; ​​ , ?

! , EvilVertex V, EvilEdge E. , object, , , .

, ?

, .

dict.Add , .

, dict Add . , Test2 , , , EvilVertex IVertex, .

+4

All Articles