How to resolve ambiguous interface method signatures that occur when several common arguments of the type are identical

In the example below, there is a way that the method of the implementing class explicitly tells the compiler which interface element it implements? I know that ambiguity can be resolved between interfaces, but here it is within the same interface.

interface IFoo<A,B> { void Bar(A a); void Bar(B b); } class Foo : IFoo<string, string> { public void Bar(string a) { } public void Bar(string b) { } // ambiguous signature } 
+6
source share
3 answers

I don’t think you can solve this directly using only one interface, because method signatures can be combined for some cases.

If you really need this function, I think you should introduce a new interface, which will be obtained using foo.

 public interface IBar<T> { void Bar(T t); } public interface IFoo<A, B> : IBar<A> { void Bar(B b); } 

Now you can explicitly implement both interfaces:

 public class Foo : IFoo<string, string> { void IFoo<string, string>.Bar(string b) { Console.WriteLine("IFoo<string, string>.Bar: " + b); } void IBar<string>.Bar(string t) { Console.WriteLine("IBar<string>.Bar: " + t); } } 

But if you want to use it, you must point your instance to a special interface:

 var foo = new Foo(); ((IFoo<string, string>)foo).Bar("Hello"); ((IBar<string>foo).Bar("World"); 

Will print as expected:

 IFoo<string, string>.Bar: Hello IBar<string>.Bar: World 

Hope this helps you. I do not think there is another way to do this.

You can only implement one interface explicitly, so you only need to cast if you want to call another method.

+2
source

You just need to remove the duplicate row:

 interface IFoo<A, B> { void Bar(A a); void Bar(B b); } class Foo : IFoo<string, string> { public void Bar(string a) { } } 

In this case, the presence of a single implementation of void Bar(string a) implements both methods of the interface.

Actually calling interfaces is much more complicated. You need a reflection.

+1
source

You cannot do this.

Bar() will be mixed in this situation. Try changing the interface methods to BarA() , BarB() .

Also consider making A and B more meaningful names (e.g. IFoo<TKey, TValue> ), then your methods can be BarKey() and BarValue() .

0
source

All Articles