Unification of type parameters

Why is this forbidden in C #? alt text http://img706.imageshack.us/img706/7360/restriction.png

In fact, I would like to write

alias Y<A, B> : X<A, B>, X<B, A> 

Pooling is really desirable here; if A = B, then only one method should be defined.

+4
source share
2 answers

The first reason that comes to mind is the following.

 class Example : Y<int,int> { ... } 

In this case, type Y implements the same interface twice, but may have different implementations of the same method. This creates an unsolvable ambiguity in the compiler for the Tx method, both for implementation and for invocation.

For example, complete the following task.

 class OtherExample<A,B> : Y<A,B> { B Tx(A x) { Console.WriteLine("Top method in the file"); return default(B); } A Tx(B x) { Console.WriteLine("Bottom method in the file"); return default(A); } } 

If you ignore the merge error, this is the legal implementation of Y<A,B> . Now imagine that the user has completed the following

 var v1 = new OtherExample<int,int>(); v1.Tx(42); 

What exactly will happen in this scenario? How could the compiler or CLR solve this ambiguity? You would have identically named methods with identical signatures.

+6
source

Instead, you could define your type as:

 public interface Y<A> : X<A,A> { } 
+2
source

Source: https://habr.com/ru/post/1303852/


All Articles